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
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 }Advertisements