How can I display only unique record from MongoDB and ignore the duplicates?

MongoDBDatabaseBig Data Analytics

To display only unique records, use distinct() in MongoDB. Let us create a collection with documents −

> db.demo613.insertOne({"Name":"Chris"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988bd4f6b89257f5584d88")
}
> db.demo613.insertOne({"Name":"Bob"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988bdbf6b89257f5584d89")
}
> db.demo613.insertOne({"Name":"Bob"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988bddf6b89257f5584d8a")
}
> db.demo613.insertOne({"Name":"David"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988be0f6b89257f5584d8b")
}
> db.demo613.insertOne({"Name":"Chris"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988be2f6b89257f5584d8c")
}
> db.demo613.insertOne({"Name":"Sam"});{
   "acknowledged" : true, "insertedId" : ObjectId("5e988be8f6b89257f5584d8d")
}

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

> db.demo613.find();

This will produce the following output −

{ "_id" : ObjectId("5e988bd4f6b89257f5584d88"), "Name" : "Chris" }
{ "_id" : ObjectId("5e988bdbf6b89257f5584d89"), "Name" : "Bob" }
{ "_id" : ObjectId("5e988bddf6b89257f5584d8a"), "Name" : "Bob" }
{ "_id" : ObjectId("5e988be0f6b89257f5584d8b"), "Name" : "David" }
{ "_id" : ObjectId("5e988be2f6b89257f5584d8c"), "Name" : "Chris" }
{ "_id" : ObjectId("5e988be8f6b89257f5584d8d"), "Name" : "Sam" }

Following is the query to get a unique record −

> db.demo613.distinct("Name");

This will produce the following output −

[ "Chris", "Bob", "David", "Sam" ]
raja
Published on 15-May-2020 11:41:01
Advertisements