Display a value with $addToSet in MongoDB with no duplicate elements?


Use $addToSet operator to ensures that there are no duplicate items added to the set. Let us first create a collection with documents −

> db.getDistinctDemo.insertOne({"Values":[100,200]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cef69f9ef71edecf6a1f69d")
}
> db.getDistinctDemo.insertOne({"Values":[300,100]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cef6a07ef71edecf6a1f69e")
}

Display all documents from a collection with the help of find() method −

> db.getDistinctDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cef69f9ef71edecf6a1f69d"),
   "Values" : [
      100,
      200
   ]
}
{
   "_id" : ObjectId("5cef6a07ef71edecf6a1f69e"),
   "Values" : [
      300,
      100
   ]
}

Following is the query to get distinct levels of array field in MongoDB −

> db.getDistinctDemo.aggregate([    
   { "$group": { "_id": 0,            
      "MyValues": { "$addToSet": "$Values" }      
   } }
]);

This will produce the following output −

{ "_id" : 0, "MyValues" : [ [ 300, 100 ], [ 100, 200 ] ] }
raja
Published on 14-Jun-2019 17:07:57
Advertisements