1

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
          ]
        }
      }
    }
  }
}
}

1 Answer 1

1

You can use below aggregation

{
  "$addFields": {
    "unreaded_messages": {
      "$size": {
        "$filter": {
          "input": "$notification",
          "cond": {
            "$eq": ["$$this.readed", false]
          }
        }
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.