MongoDB数组Match聚合不符合预期:精确匹配返回异常结果
Let’s break down exactly what’s happening here and how to fix it:
The root of the confusion
Your current query {"NUM": {$gte: 25, $lte:25}} isn’t checking for an element exactly equal to 25 in the array. MongoDB interprets this range condition differently for array fields:
Does the
NUMarray contain at least one element that is >=25 AND at least one element that is <=25?
For the document with _id:3, the array [24,26,28] meets both criteria:
- 26 is >=25
- 24 is <=25
Even though no single element is exactly 25, the combination of these two elements satisfies the query’s conditions—so the document gets returned.
The fix for exact matching
When your from and to parameters are identical (and you want to find arrays that contain that exact value), use a direct equality match instead of range operators:
db.runCommand( { aggregate: "mycoll", pipeline: [ { "$match": {"NUM": 25 } } ] } )
This query will only return documents where the NUM array includes the exact value 25. For your sample data, this correctly returns only the document with _id:2.
Bonus: Ensuring a single element meets both range conditions
If you ever need to verify that one element in the array satisfies all range conditions (not separate elements), use the $elemMatch operator. While it’s unnecessary for exact matches, it’s useful for more complex range checks:
db.runCommand( { aggregate: "mycoll", pipeline: [ { "$match": {"NUM": { $elemMatch: { $gte:25, $lte:25 } } } } ] } )
$elemMatch forces MongoDB to check that a single element in the array meets all specified conditions—here, that means an element equal to 25.
内容的提问来源于stack exchange,提问作者Kamlesh Kanazariya




