Reputation: 2467
I know how to write a query such that I can count the number of items in an array per document using $size
.
db.collection.aggregate(
{project : {"name" : 1, _id:0, sizeOf : {$size : "$People.Age"}}}
)
How do I write a query using $size
, but I only want to count the field if it equals a certain value (for example People.Ages.Current_Age : 21
). I'm assuming I'd use $eq
for that?
Sample Code:
{
"People" : [
{
"Name" : "Jen",
"Ages" : {
"Current_Age" : 32,
"Graduate_Age" : 26,
}
},
{
"Name" : "Bill",
"Ages" : {
"Current_Age" : 30,
"Graduate_Age" : 22,
}
},
{
"Name" : "Josh",
"Ages" : {
"Current_Age" : 27,
"Graduate_Age" : 24,
}
}
]
}
Upvotes: 1
Views: 1399
Reputation: 46491
You can use below aggregation
db.collection.aggregate([
{ "$project": {
"name": 1, "_id": 0,
"sizeOf": {
"$size": {
"$filter": {
"input": "$People",
"as": "people",
"cond": { "$eq": ["$$people.Ages.Current_Age", 21] }
}
}
}
}}
])
Upvotes: 1
Reputation: 165
You can use filter operator here, filter the array before taking size.
db.collection.aggregate(
{project : {"name" : 1, _id:0, sizeOf : {$size : {
$filter: {
input: "$People.Age",
as: "age",
cond: { $eq:[$$age, 21] }
}
}}}}
)
Upvotes: 0