Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I display only unique record from MongoDB and ignore the duplicates?
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" ]
Advertisements