
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
Group Duplicate Documents in MongoDB
To group duplicate documents, use MongoDB aggregate(). Let us create a collection with documents −
> db.demo501.insertOne({"Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8752f0987b6e0e9d18f566") } > db.demo501.insertOne({"Name":"Bob"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8752f4987b6e0e9d18f567") } > db.demo501.insertOne({"Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8752f8987b6e0e9d18f568") } > db.demo501.insertOne({"Name":"John"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8752fb987b6e0e9d18f569") } > db.demo501.insertOne({"Name":"Chris"});{ "acknowledged" : true, "insertedId" : ObjectId("5e8752fd987b6e0e9d18f56a") } > db.demo501.insertOne({"Name":"John"});{ "acknowledged" : true, "insertedId" : ObjectId("5e875301987b6e0e9d18f56b") } > db.demo501.insertOne({"Name":"David"});{ "acknowledged" : true, "insertedId" : ObjectId("5e875307987b6e0e9d18f56c") }
Display all documents from a collection with the help of find() method −
> db.demo501.find();
This will produce the following output −
{ "_id" : ObjectId("5e8752f0987b6e0e9d18f566"), "Name" : "Chris" } { "_id" : ObjectId("5e8752f4987b6e0e9d18f567"), "Name" : "Bob" } { "_id" : ObjectId("5e8752f8987b6e0e9d18f568"), "Name" : "Chris" } { "_id" : ObjectId("5e8752fb987b6e0e9d18f569"), "Name" : "John" } { "_id" : ObjectId("5e8752fd987b6e0e9d18f56a"), "Name" : "Chris" } { "_id" : ObjectId("5e875301987b6e0e9d18f56b"), "Name" : "John" } { "_id" : ObjectId("5e875307987b6e0e9d18f56c"), "Name" : "David" }
Following is the query to group duplicate documents in MongoDB −
> db.demo501.aggregate( [ { $group : { _id : "$Name" } } ] )
This will produce the following output −
{ "_id" : "David" } { "_id" : "John" } { "_id" : "Bob" } { "_id" : "Chris" }
Advertisements