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
Select documents grouped by field in MongoDB?
To select documents grouped by field in MongoDB, use $group along with $project. Let us first create a collection with documents −
> db.demo540.insertOne({id:1,"Name":"Chris","CountryName":"US"});{
"acknowledged" : true, "insertedId" : ObjectId("5e8ca368ef4dcbee04fbbc0e")
}
> db.demo540.insertOne({id:1,"Name":"Chris","CountryName":"UK"});{
"acknowledged" : true, "insertedId" : ObjectId("5e8ca36bef4dcbee04fbbc0f")
}
> db.demo540.insertOne({id:1,"Name":"Chris","CountryName":"AUS"});{
"acknowledged" : true, "insertedId" : ObjectId("5e8ca370ef4dcbee04fbbc10")
}
Display all documents from a collection with the help of find() method −
> db.demo540.find();
This will produce the following output −
{ "_id" : ObjectId("5e8ca368ef4dcbee04fbbc0e"), "id" : 1, "Name" : "Chris", "CountryName" :
"US" }
{ "_id" : ObjectId("5e8ca36bef4dcbee04fbbc0f"), "id" : 1, "Name" : "Chris", "CountryName" :
"UK" }
{ "_id" : ObjectId("5e8ca370ef4dcbee04fbbc10"), "id" : 1, "Name" : "Chris", "CountryName" :
"AUS" }
Following is the query to select documents grouped by field −
> var query= [
... {
... "$group": {
... "_id": {
... "id": "$id",
... "Name": "$Name"
... },
... "details": {
... "$push": {
...
... "CountryName": "$CountryName"
...
... }
... }
... }
... },
... {
... "$project": {
... "_id": "$_id.id",
... "Name": "$_id.Name",
... "details": 1
... }
... }
... ];
> db.demo540.aggregate(q).pretty();
This will produce the following output −
{
"details" : [
{
"Name" : "Chris",
"CountryName" : "US"
},
{
"Name" : "Chris",
"CountryName" : "UK"
},
{
"Name" : "Chris",
"CountryName" : "AUS"
}
],
"_id" : 1,
"Name" : "Chris"
}Advertisements