Get all embedded documents with "isMarried" status in a MongoDB collection

To get all embedded documents with specific fields in MongoDB, use the $project aggregation operator. This allows you to extract and display specific fields from embedded documents.

Syntax

db.collection.aggregate([
    {
        $project: {
            "fieldName": "$embeddedDocument.fieldName",
            "anotherField": "$embeddedDocument.anotherField"
        }
    }
]);

Sample Data

db.demo220.insertMany([
    {
        "id": 101,
        "FullName": "John Doe",
        "EmailId": "john12@gmail.com",
        "ShippingDate": new ISODate(),
        "details": { "_id": 1001, "isMarried": true }
    },
    {
        "id": 102,
        "FullName": "John Smith",
        "EmailId": "johnsmith@gmail.com",
        "ShippingDate": new ISODate(),
        "details": { "_id": 1002, "isMarried": false }
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3eaf5b03d395bdc213471d"),
        ObjectId("5e3eaf5c03d395bdc213471e")
    ]
}

Display All Documents

db.demo220.find();
{ "_id": ObjectId("5e3eaf5b03d395bdc213471d"), "id": 101, "FullName": "John Doe", "EmailId": "john12@gmail.com", "ShippingDate": ISODate("2020-02-08T12:53:47.876Z"), "details": { "_id": 1001, "isMarried": true } }
{ "_id": ObjectId("5e3eaf5c03d395bdc213471e"), "id": 102, "FullName": "John Smith", "EmailId": "johnsmith@gmail.com", "ShippingDate": ISODate("2020-02-08T12:53:48.991Z"), "details": { "_id": 1002, "isMarried": false } }

Extract Embedded Document Fields

Use $project to extract the "isMarried" status from the embedded "details" document ?

db.demo220.aggregate([
    {
        $project: {
            "isMarried": "$details.isMarried",
            "detailsId": "$details._id"
        }
    }
]);
{ "_id": ObjectId("5e3eaf5b03d395bdc213471d"), "isMarried": true, "detailsId": 1001 }
{ "_id": ObjectId("5e3eaf5c03d395bdc213471e"), "isMarried": false, "detailsId": 1002 }

Key Points

  • Use dot notation with $ prefix to access embedded document fields: "$details.isMarried"
  • $project creates new fields in the output while maintaining the original _id
  • You can extract multiple fields from the same embedded document in one projection

Conclusion

The $project aggregation operator efficiently extracts specific fields from embedded documents using dot notation. This approach provides clean, focused results containing only the required embedded data.

Updated on: 2026-03-15T01:59:10+05:30

256 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements