How to sort, select and query subdocument in MongoDB?

To sort, select and query subdocument in MongoDB, use the aggregation pipeline with $unwind, $project, and $sort stages. This approach extracts subdocument fields, selects specific fields, and sorts the results.

Syntax

db.collection.aggregate([
    { $unwind: "$subdocumentField" },
    { $project: { 
        field1: "$subdocumentField.field1",
        field2: "$subdocumentField.field2"
    }},
    { $sort: { field1: 1 } }
]);

Sample Data

db.demo236.insertMany([
    {"details":{"Name":"Chris","Age":21}},
    {"details":{"Name":"David","Age":23}},
    {"details":{"Name":"Bob","Age":24}}
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5e419015f4cebbeaebec514c"),
        ObjectId("5e41901cf4cebbeaebec514d"),
        ObjectId("5e419023f4cebbeaebec514e")
    ]
}

Display Current Documents

db.demo236.find();
{ "_id" : ObjectId("5e419015f4cebbeaebec514c"), "details" : { "Name" : "Chris", "Age" : 21 } }
{ "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "details" : { "Name" : "David", "Age" : 23 } }
{ "_id" : ObjectId("5e419023f4cebbeaebec514e"), "details" : { "Name" : "Bob", "Age" : 24 } }

Sort, Select and Query Subdocument

Extract subdocument fields, project specific fields, and sort by Name in descending order ?

db.demo236.aggregate([
    { $unwind: "$details" },
    { $project: {
        Name: "$details.Name",
        Age: "$details.Age"
    }},
    { $sort: {Name: -1}}
]);
{ "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e419015f4cebbeaebec514c"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e419023f4cebbeaebec514e"), "Name" : "Bob", "Age" : 24 }

How It Works

  • $unwind extracts the subdocument and creates separate documents
  • $project selects and reshapes specific fields from the subdocument
  • $sort orders results by the specified field (-1 for descending, 1 for ascending)

Conclusion

Use MongoDB aggregation pipeline to effectively sort, select and query subdocuments. The combination of $unwind, $project, and $sort provides powerful subdocument manipulation capabilities.

Updated on: 2026-03-15T02:01:21+05:30

310 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements