Performing distinct on multiple fields in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use $group operator along with aggregate framework to perform distinct on multiple fields. Let us first create a collection with documents −

> db.distinctOnMultipleFieldsDemo.insertOne(
...    {
...       "StudentFirstName" : "Chris",
...       "StudentAge" : 21,
...       "StudentCountryName": "US"
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2e518b64f4b851c3a13d7")
}
> db.distinctOnMultipleFieldsDemo.insertOne(
...    {
...       "StudentFirstName" : "Robert",
...       "StudentAge" : 21,
...       "StudentCountryName": "AUS"
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2e518b64f4b851c3a13d8")
}
> db.distinctOnMultipleFieldsDemo.insertOne(
...    {
...       "StudentFirstName" : "Chris",
...       "StudentAge" : 22,
...       "StudentCountryName": "UK"
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2e518b64f4b851c3a13d9")
}
> db.distinctOnMultipleFieldsDemo.insertOne(
...    {
...       "StudentFirstName" : "David",
...       "StudentAge" : 24,
...       "StudentCountryName": "AUS"
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2e518b64f4b851c3a13da")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5cd2e518b64f4b851c3a13d7"),
   "StudentFirstName" : "Chris",
   "StudentAge" : 21,
   "StudentCountryName" : "US"
}
{
   "_id" : ObjectId("5cd2e518b64f4b851c3a13d8"),
   "StudentFirstName" : "Robert",
   "StudentAge" : 21,
   "StudentCountryName" : "AUS"
}
{
   "_id" : ObjectId("5cd2e518b64f4b851c3a13d9"),
   "StudentFirstName" : "Chris",
   "StudentAge" : 22,
   "StudentCountryName" : "UK"
}
{
   "_id" : ObjectId("5cd2e518b64f4b851c3a13da"),
   "StudentFirstName" : "David",
   "StudentAge" : 24,
   "StudentCountryName" : "AUS"
}

Following is the query to perform distinct on multiple fields in MongoDB −

> db.distinctOnMultipleFieldsDemo.aggregate([
...    {
...       $group:
...       {
...          _id:0,
...          StudentFirstName: {$addToSet: '$StudentFirstName'},
...          StudentAge: {$addToSet: '$StudentAge'},
...          StudentCountryName: {$addToSet: '$StudentCountryName'},
...    }}
... ]);

This will produce the following output −

{ "_id" : 0, "StudentFirstName" : [ "David", "Robert", "Chris" ], "StudentAge" : [ 24, 22, 21 ], "StudentCountryName" : [ "UK", "AUS", "US" ] }
raja
Published on 22-May-2019 11:35:07
Advertisements