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

To group records in MongoDB and display specific values using dot notation, use the $group aggregation stage with field references like "$details.Name" to extract values from nested documents or arrays.

Syntax

db.collection.aggregate([
    {
        $group: {
            "_id": { "fieldName": "$arrayField.nestedField" }
        }
    }
]);

Sample Data

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

Display all documents from the collection ?

db.demo430.find();
{
    "_id": ObjectId("5e7702ddbbc41e36cc3cae88"),
    "details": [
        { "Name": "Chris" },
        { "Name": "David" },
        { "Name": "Adam" },
        { "Name": "Bob" }
    ]
}

Example: Group Records with Dot Notation

Group records and extract all Name values from the details array ?

db.demo430.aggregate([
    {
        $group: {
            "_id": { "Name": "$details.Name" }
        }
    }
]);
{
    "_id": {
        "Name": ["Chris", "David", "Adam", "Bob"]
    }
}

How It Works

  • The $group stage groups documents by specified criteria.
  • Dot notation "$details.Name" extracts all Name values from the details array.
  • When applied to arrays, it returns all matching field values as an array.

Conclusion

Use $group with dot notation field references to group documents and extract specific nested values. The "$arrayField.nestedField" syntax automatically collects all matching values from array elements.

Updated on: 2026-03-15T02:57:34+05:30

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements