MongoDB query to group duplicate documents

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 13-May-2020 06:03:42
Advertisements