Reputation: 14904
in my collection i have an document that contains following array (simplyfied):
notifications: [
{
message: "i am an message",
readed: false
},
{
message: "i am an message",
readed: false
},
{
message: "i am an message",
readed: true
},
{
message: "i am an message",
readed: true
}
]
I want to count all fields with readed:false
so that is my expected result:
{
unreaded_messages: 2
}
I have tried to add an field and to map over the notification array and to add all unreaded elements. after that i wanted to get the size with $size
so i get an number. But it doesnt worked how i expected.
{
$addFields: {
unreaded_messages: {
$map: {
input: "$notification",
in: {
check: {
$eq: [
"$$this.readed",
false
]
}
}
}
}
}
}
Upvotes: 1
Views: 121
Reputation: 46451
You can use below aggregation
{
"$addFields": {
"unreaded_messages": {
"$size": {
"$filter": {
"input": "$notification",
"cond": {
"$eq": ["$$this.readed", false]
}
}
}
}
}
}
Upvotes: 1