bpGusar
bpGusar

Reputation: 127

How to get the number of objects in an array that match the required parameters in mongodb?

I have array like

messages: [{
                message: "message",
                from: someId,
                createdAt: Date.now(),
                read: false
              },
{
                message: "message",
                from: someId,
                createdAt: Date.now(),
                read: false
              },
...
]

How can I get number of this objects that match the parameter read === false

Upvotes: 0

Views: 47

Answers (1)

matthPen
matthPen

Reputation: 4343

As your message is an array, you can do it with aggregation framework :

db.collection.aggregate([
  {
    $addFields: {
      unread: {
        $size: {
          $filter: {
            input: "$messages",
            as: "message",
            cond: {
              $eq: [
                "$$message.read",
                false
              ]
            }
          }
        }
      }
    }
  }
])

You can test it here

Upvotes: 2

Related Questions