Get distinct levels of array field in MongoDB?

MongoDBDatabaseBig Data Analytics

To get distinct levels of array field, use $addToSet in MongoDB. Let us create a collection with documents −

> db.demo122.insertOne({"ListOfValues":[100,10]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2f20f1140daf4c2a3544b6")
}
> db.demo122.insertOne({"ListOfValues":[240,10]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2f20f7140daf4c2a3544b7")
}

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

> db.demo122.find();

This will produce the following output −

{ "_id" : ObjectId("5e2f20f1140daf4c2a3544b6"), "ListOfValues" : [ 100, 10 ] }
{ "_id" : ObjectId("5e2f20f7140daf4c2a3544b7"), "ListOfValues" : [ 240, 10 ] }

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

> db.demo122.aggregate([
...    {
...       "$group": {
...          "_id": 0,
...          "ListOfValues": { "$addToSet": "$ListOfValues" }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : 0, "ListOfValues" : [ [ 240, 10 ], [ 100, 10 ] ] }
raja
Published on 31-Mar-2020 11:32:27
Advertisements