Accessing array values in a MongoDB collection to fetch a specific document

To access array values in MongoDB and fetch a specific document, use dot notation to query nested fields within arrays. This allows you to search for documents containing specific values in their array elements.

Syntax

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

Sample Data

Let us create a collection with documents containing ProductDetails arrays ?

db.demo326.insertMany([
    {
        "id": 101,
        "ProductDetails": [
            { "ProductId": "Prod-101", "ProductName": "Product-1" },
            { "ProductId": "Prod-102", "ProductName": "Product-2" }
        ]
    },
    {
        "id": 103,
        "ProductDetails": [
            { "ProductId": "Prod-104", "ProductName": "Product-5" },
            { "ProductId": "Prod-105", "ProductName": "Product-6" }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e516751f8647eb59e562074"),
        ObjectId("5e516771f8647eb59e562075")
    ]
}

Display All Documents

db.demo326.find();
{
    "_id": ObjectId("5e516751f8647eb59e562074"), 
    "id": 101, 
    "ProductDetails": [
        { "ProductId": "Prod-101", "ProductName": "Product-1" },
        { "ProductId": "Prod-102", "ProductName": "Product-2" }
    ]
}
{
    "_id": ObjectId("5e516771f8647eb59e562075"), 
    "id": 103, 
    "ProductDetails": [
        { "ProductId": "Prod-104", "ProductName": "Product-5" },
        { "ProductId": "Prod-105", "ProductName": "Product-6" }
    ]
}

Access Array Values to Fetch Specific Document

Query to find the document containing ProductId "Prod-104" within the ProductDetails array ?

db.demo326.find({ "ProductDetails.ProductId": "Prod-104" });
{
    "_id": ObjectId("5e516771f8647eb59e562075"), 
    "id": 103, 
    "ProductDetails": [
        { "ProductId": "Prod-104", "ProductName": "Product-5" },
        { "ProductId": "Prod-105", "ProductName": "Product-6" }
    ]
}

Conclusion

Use dot notation with array field names to query nested values in MongoDB arrays. The syntax "arrayName.fieldName" matches documents containing the specified value in any array element, returning the entire matching document.

Updated on: 2026-03-15T02:30:41+05:30

280 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements