Getting distinct values from object array in MongoDB?

MongoDBDatabaseBig Data Analytics

To get distinct values from object array in MongoDB, use distinct(). Let us create a collection with documents −

> db.demo442.insertOne(
...    {
...
...       "Information" : [
...          {
...             "FirstName" : "John",
...             "Age" : 21
...          },
...          {
...             "FirstName" : "Sam",
...             "Age" : 23
...          },
...          {
...             "FirstName" : "John",
...             "Age" : 24
...          },
...          {
...             "FirstName" : "Carol",
...             "Age" : 20
...          },
...          {
...             "FirstName" : "Sam",
...             "Age" : 22
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e78cf29bbc41e36cc3caeb8")
}

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

> db.demo442.find();

This will produce the following output −

{ "_id" : ObjectId("5e78cf29bbc41e36cc3caeb8"), "Information" : [ { "FirstName" : "John", "Age" : 21 }, { "FirstName" : "Sam", "Age" : 23 }, { "FirstName" : "John", "Age" : 24 }, { "FirstName" : "Carol", "Age" : 20 }, { "FirstName" : "Sam", "Age" : 22 } ] }

Following is the query to get distinct values from object array in MongoDB −

> db.demo442.distinct("Information.FirstName");

This will produce the following output −

[ "Carol", "John", "Sam" ]
raja
Published on 06-Apr-2020 13:26:24
Advertisements