Count size from an array that matches condition

I have a document like:

[
  {_id:1, field: {array: [1,2,3,4,1,1] }},
  {_id:2, field: {array: [5,1,1,1,1,1] }},
  {_id:3, field: {array: [3,2,3,4,1,2] }}
]

I want to count the array elements which eq 1.

The result is:

[
  {_id: 1, count: 3},
  {_id: 2, count: 5},
  {_id: 3, count: 1}
]

Solution 1:

You can try an aggregation query,

  • $filter to iterate loop of an array and check condition if the value is 1
  • $size to get total elements of the filtered array
db.collection.aggregate([
  {
    $project: {
      count: {
        $size: {
          $filter: {
            input: "$field.array",
            cond: { $eq: ["$$this", 1] }
          }
        }
      }
    }
  }
])

Playground


The second possible option,

  • $reduce to iterate loop of array
  • $cond to check if the value is equal to 1
  • if it is 1 then $add plus one in initialValue otherwise return the same number
db.collection.aggregate([
  {
    $project: {
      count: {
        $reduce: {
          input: "$field.array",
          initialValue: 0,
          in: {
            $cond: [
              { $eq: ["$$this", 1] },
              { $add: ["$$value", 1] },
              "$$value"
            ]
          }
        }
      }
    }
  }
])

Playground