Can we search an array of objects in MongoDB?

Yes, you can search an array of objects in MongoDB using multiple approaches. The most common methods are direct field matching and the aggregation pipeline with $unwind.

Syntax

// Direct field matching
db.collection.find({"arrayField.fieldName": "value"})

// Using aggregation with $unwind
db.collection.aggregate([
    {$unwind: "$arrayField"},
    {$match: {"arrayField.fieldName": "value"}}
])

Sample Data

db.demo623.insertOne({
    _id: 1,
    details: [
        {
            Name: "Chris"
        },
        {
            DueDate: new ISODate("2020-01-10")
        },
        {
            CountryName: "US"
        }
    ]
});
{ "acknowledged" : true, "insertedId" : 1 }

Method 1: Using $unwind (Aggregation Pipeline)

Search for objects containing "Chris" in the Name field ?

db.demo623.aggregate([
    {$unwind: "$details"},
    {$match: {"details.Name": "Chris"}},
    {$project: {"details.Name": 1}}
]);
{ "_id" : 1, "details" : { "Name" : "Chris" } }

Method 2: Direct Field Matching (Simpler Approach)

For most use cases, you can directly query array fields without unwinding ?

db.demo623.find({"details.Name": "Chris"});
{
    "_id" : 1,
    "details" : [
        { "Name" : "Chris" },
        { "DueDate" : ISODate("2020-01-10T00:00:00Z") },
        { "CountryName" : "US" }
    ]
}

Key Differences

  • $unwind creates separate documents for each array element and allows complex filtering.
  • Direct matching returns the entire document when any array element matches the condition.

Conclusion

MongoDB supports searching arrays of objects through dot notation. Use direct field matching for simple queries or the aggregation pipeline with $unwind for complex transformations and filtering.

Updated on: 2026-03-15T03:11:40+05:30

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements