MongoDB query to group records and display a specific value with dot notation


Let us create a collection with documents −

> db.demo430.insertOne(
...    {
...       "details": [
...          {
...             "Name":"Chris"
...          } ,
...          {"Name":"David"},
...          {"Name":"Adam"},
...          {"Name":"Bob"}
...
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7702ddbbc41e36cc3cae88")
}

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

> db.demo430.find();

This will produce the following output −

{ "_id" : ObjectId("5e7702ddbbc41e36cc3cae88"), "details" : [ { "Name" : "Chris" }, { "Name" : "David" }, { "Name" : "Adam" }, { "Name" : "Bob" } ] }

Following is the query to group records −

> db.demo430.aggregate([{ "$group" : { "_id" : {"Name" : "$details.Name"}}}]);

This will produce the following output −

{ "_id" : { "Name" : [ "Chris", "David", "Adam", "Bob" ] } }

Updated on: 03-Apr-2020

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements