I am trying to write aggregation query in mongoDb where I want to loop over an array of objects and get count of those objects which meet certain conditions. I have array named banks[] which has 28-30 objects in it. I want to check whether "pdf" key exists in every object and check whether the value is true or false and return only count of those objects having value true. How can I do it using aggregation? Please help. Below is sample data in banks[] array.
banks[{id:1, name: "ABC","pdf": true},{id:2, name:"PQR"}, {id:3, name:"XYZ", pdf:"false"}....]
Similarly the array has 30 objects.
The output which I want for above sample is
{id:"1", count:1}
Thanks in advance!
You can use $size
to get the count of an array. $filter
is used to filter based on conditions.
{
"$project": {
count: {
$size: {
$filter: {
input: "$banks",
cond: {
$eq: [
"$$this.pdf",
true
]
}
}
}
}
}
}
Working Mongo playground
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments