How can I find documents in MongoDB based on the number of matched objects within an array?

In MongoDB, you can find documents based on the number of matched objects within an array using aggregation pipelines with $filter and $size operators, or the $where operator for JavaScript-based queries.

Syntax

// Method 1: Using Aggregation Pipeline
db.collection.aggregate([
    { $match: {
        $expr: { $gte: [
            { $size: { $filter: {
                input: "$arrayField",
                cond: { $and: [ /* conditions */ ] }
            }}}, 
            minCount
        ]}
    }}
]);

// Method 2: Using $where operator
db.collection.find({ $where: function() {
    // JavaScript logic to count matches
}});

Sample Data

db.demo694.insertMany([
    {
        "details": [
            { "Name": "Chris", "Age": 21 },
            { "Name": "David", "Age": 22 }
        ]
    },
    {
        "details": [
            { "Name": "Bob", "Age": 21 },
            { "Name": "Mike", "Age": 23 }
        ]
    },
    {
        "details": [
            { "Name": "Chris", "Age": 21 },
            { "Name": "Carol", "Age": 22 }
        ]
    }
]);

Method 1: Using Aggregation Pipeline (Recommended)

db.demo694.aggregate([
    {
        $match: {
            $expr: {
                $gte: [
                    {
                        $size: {
                            $filter: {
                                input: "$details",
                                cond: {
                                    $and: [
                                        { $eq: ["$$this.Name", "Chris"] },
                                        { $eq: ["$$this.Age", 21] }
                                    ]
                                }
                            }
                        }
                    },
                    1
                ]
            }
        }
    }
]);

Method 2: Using $where Operator

nameChrisAge21 = function () {
    var count = 0;
    this.details.forEach(function (d) {
        if (d.Name == "Chris" && d.Age == 21) {
            count++;
        }
    });
    return count >= 1;
}

db.demo694.find({ $where: nameChrisAge21 });
{ "_id" : ObjectId("5ea59279ece4e5779399c07f"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 22 } ] }
{ "_id" : ObjectId("5ea5927aece4e5779399c081"), "details" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Carol", "Age" : 22 } ] }

Key Points

  • The aggregation method is preferred for performance as it uses MongoDB's optimized operators.
  • $filter creates an array of matching elements, and $size counts them.
  • $where executes JavaScript but is slower and cannot use indexes effectively.

Conclusion

Use aggregation pipelines with $filter and $size for efficient array element counting. The $where operator provides flexibility but sacrifices performance for complex JavaScript logic.

Updated on: 2026-03-15T03:38:39+05:30

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements