Search an array of hashes in MongoDB?

To search an array of hashes in MongoDB, use dot notation to access fields within the hash objects stored in the array. This allows you to query specific key-value pairs within nested hash structures.

Syntax

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

Sample Data

db.searchAnArrayDemo.insertMany([
    { _id: 1, "TechnicalDetails": [{ "Language": "MongoDB" }] },
    { _id: 2, "TechnicalDetails": [{ "Language": "MySQL" }] },
    { _id: 3, "TechnicalDetails": [{ "Language": "MongoDB" }] },
    { _id: 4, "TechnicalDetails": [{ "Language": "MongoDB" }] },
    { _id: 5, "TechnicalDetails": [{ "Language": "Java" }] }
]);
{
    "acknowledged": true,
    "insertedIds": {
        "0": 1, "1": 2, "2": 3, "3": 4, "4": 5
    }
}

Display All Documents

db.searchAnArrayDemo.find().pretty();
{ "_id": 1, "TechnicalDetails": [{ "Language": "MongoDB" }] }
{ "_id": 2, "TechnicalDetails": [{ "Language": "MySQL" }] }
{ "_id": 3, "TechnicalDetails": [{ "Language": "MongoDB" }] }
{ "_id": 4, "TechnicalDetails": [{ "Language": "MongoDB" }] }
{ "_id": 5, "TechnicalDetails": [{ "Language": "Java" }] }

Search Array of Hashes

Count documents where TechnicalDetails array contains a hash with Language field equal to "MongoDB" ?

db.searchAnArrayDemo.find({ "TechnicalDetails.Language": "MongoDB" }).count();
3

Find Matching Documents

Retrieve all documents that match the search criteria ?

db.searchAnArrayDemo.find({ "TechnicalDetails.Language": "MongoDB" });
{ "_id": 1, "TechnicalDetails": [{ "Language": "MongoDB" }] }
{ "_id": 3, "TechnicalDetails": [{ "Language": "MongoDB" }] }
{ "_id": 4, "TechnicalDetails": [{ "Language": "MongoDB" }] }

Conclusion

Use dot notation to search within array elements containing hash objects. MongoDB automatically searches all elements in the array when you specify a field path like "arrayName.fieldName".

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

277 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements