MongoDB query to group by _id



To group by _id in MongoDB, use $group. Let us create a collection with documents −

> db.demo529.insertOne({"Score":10});{    "acknowledged" : true,    "insertedId" : ObjectId("5e8b1d5bef4dcbee04fbbbe4") } > db.demo529.insertOne({"Score":20});{    "acknowledged" : true,    "insertedId" : ObjectId("5e8b1d5fef4dcbee04fbbbe5") } > db.demo529.insertOne({"Score":10});{    "acknowledged" : true,    "insertedId" : ObjectId("5e8b1d61ef4dcbee04fbbbe6") } > db.demo529.insertOne({"Score":10});{    "acknowledged" : true,    "insertedId" : ObjectId("5e8b1d62ef4dcbee04fbbbe7") }

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

> db.demo529.find();

This will produce the following output −

{ "_id" : ObjectId("5e8b1d5bef4dcbee04fbbbe4"), "Score" : 10 } { "_id" : ObjectId("5e8b1d5fef4dcbee04fbbbe5"), "Score" : 20 } { "_id" : ObjectId("5e8b1d61ef4dcbee04fbbbe6"), "Score" : 10 } { "_id" : ObjectId("5e8b1d62ef4dcbee04fbbbe7"), "Score" : 10 }

Following is the query to group by _id −

> db.demo529.aggregate( [ ... { ...    $group: { ...       _id: null, ...       count: { $sum: 1 } ...    } ... } ... ] )

This will produce the following output −

{ "_id" : null, "count" : 4 }
Updated on: 2020-05-13T07:41:39+05:30

924 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements