MongoDB query for fields in embedded document?

To query fields in embedded documents in MongoDB, use dot notation to navigate through the nested structure. For arrays of embedded documents, MongoDB searches through all array elements and returns the entire document when a match is found.

Syntax

db.collection.find({"arrayName.fieldName": value});

Sample Data

Let us first create a collection with embedded documents:

db.embeddedDocumentDemo.insertOne({
    "CustomerDetails": [
        {"CustomerName": "Chris", "CustomerPurchasePrice": 3000},
        {"CustomerName": "Robert", "CustomerPurchasePrice": 4500},
        {"CustomerName": "David", "CustomerPurchasePrice": 1000}
    ]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5cd32347edc6604c74817ccd")
}

Display all documents from the collection:

db.embeddedDocumentDemo.find().pretty();
{
    "_id": ObjectId("5cd32347edc6604c74817ccd"),
    "CustomerDetails": [
        {
            "CustomerName": "Chris",
            "CustomerPurchasePrice": 3000
        },
        {
            "CustomerName": "Robert",
            "CustomerPurchasePrice": 4500
        },
        {
            "CustomerName": "David",
            "CustomerPurchasePrice": 1000
        }
    ]
}

Example: Query by Purchase Price

Find documents where any customer has a purchase price of 4500:

db.embeddedDocumentDemo.find({"CustomerDetails.CustomerPurchasePrice": 4500});
{
    "_id": ObjectId("5cd32347edc6604c74817ccd"),
    "CustomerDetails": [
        {"CustomerName": "Chris", "CustomerPurchasePrice": 3000},
        {"CustomerName": "Robert", "CustomerPurchasePrice": 4500},
        {"CustomerName": "David", "CustomerPurchasePrice": 1000}
    ]
}

Key Points

  • Use dot notation to access nested fields: "arrayName.fieldName"
  • MongoDB searches through all elements in the array automatically
  • Returns the entire document when any array element matches the condition

Conclusion

MongoDB's dot notation provides a simple way to query embedded document fields. When querying arrays of embedded documents, MongoDB examines all array elements and returns complete documents containing matching elements.

Updated on: 2026-03-15T01:07:12+05:30

285 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements