Querying array of Embedded Documents in MongoDB based on Range?

To query an array of embedded documents based on range, use the $filter operator within an aggregation pipeline. This allows filtering array elements that match specific criteria while preserving the document structure.

Syntax

db.collection.aggregate([
    {
        $addFields: {
            "arrayField": {
                $filter: {
                    input: "$arrayField",
                    cond: {
                        $and: [
                            { $gte: ["$$this.field", minValue] },
                            { $lte: ["$$this.field", maxValue] }
                        ]
                    }
                }
            }
        }
    }
]);

Sample Data

db.demo346.insertMany([
    {
        _id: 101,
        userDetails: [
            { UserName: "Chris", Score: 78 },
            { UserName: "David", Score: 68 },
            { UserName: "Bob", Score: 88 }
        ]
    },
    {
        _id: 102,
        userDetails: [
            { UserName: "Mike", Score: 92 },
            { UserName: "Sam", Score: 62 },
            { UserName: "Carol", Score: 97 }
        ]
    }
]);
{
    "acknowledged": true,
    "insertedIds": { "0": 101, "1": 102 }
}

Example: Filter Scores Between 80-99

Find users with scores in the range 80-99 ?

db.demo346.aggregate([
    {
        $addFields: {
            "userDetails": {
                $filter: {
                    input: "$userDetails",
                    cond: {
                        $and: [
                            { $gte: ["$$this.Score", 80] },
                            { $lte: ["$$this.Score", 99] }
                        ]
                    }
                }
            }
        }
    }
]);
{ "_id": 101, "userDetails": [ { "UserName": "Bob", "Score": 88 } ] }
{ "_id": 102, "userDetails": [ { "UserName": "Mike", "Score": 92 }, { "UserName": "Carol", "Score": 97 } ] }

How It Works

  • $addFields replaces the original array with filtered results
  • $filter examines each array element using $$this reference
  • $and combines multiple conditions for range filtering
  • $gte/$lte define the minimum and maximum bounds

Conclusion

Use $filter within aggregation pipelines to query embedded document arrays based on range conditions. This approach maintains document structure while returning only matching array elements.

Updated on: 2026-03-15T02:34:26+05:30

282 Views

Advertisements