There are multiple ways to perform the expected behaviour:
- using aggregation pipeline,
$unwind and $count the result after $match
db.collection.aggregate([
{
"$match": {
OrderId: 999
}
},
{
"$unwind": "$OrderItems"
},
{
"$match": {
"OrderItems.QuantityOrdered": 3
}
},
{
"$count": "count"
}
])
Mongo Playground
- using project option to
$filter the result obtain the count directly with $size
db.collection.find({
"OrderId": 999,
"OrderItems.QuantityOrdered": 3
},
{
"count": {
"$reduce": {
"input": "$OrderItems",
"initialValue": 0,
"in": {
"$cond": {
"if": {
"$eq": [
"$$this.QuantityOrdered",
3
]
},
"then": {
"$add": [
1,
"$$value"
]
},
"else": "$$value"
}
}
}
}
})
Mongo Playground
- The best way in my opinion will be refactoring the collection to store
OrderItems as individual documents. A simple count should be enough.
[
{
"OrderId": NumberLong(999),
"QuantityOrdered": 5
},
{
"OrderId": NumberLong(999),
"QuantityOrdered": 1
},
{
"OrderId": NumberLong(999),
"QuantityOrdered": 3
},
{
"OrderId": NumberLong(999),
"QuantityOrdered": 4
},
{
"OrderId": NumberLong(999),
"QuantityOrdered": 3
},
{
"OrderId": NumberLong(999),
"QuantityOrdered": 2
}
]
query:
db.collection.count({
"OrderId": 999,
"QuantityOrdered": 3
})
Mongo Playground