如何计算mongodb中数组中的对象?

How to count objects in an array in mongodb?

我想计算 quantity 为 3 的对象在 _id 为 1 的文档中的数组中。

{
   _id: 0,
   items: [
     { item_id: 43, quantity: 2, price: 10 },
     { item_id: 2, quantity: 1, price: 240 }
   ]
}
{
   _id: 1,
   items: [
     { item_id: 23, quantity: 3, price: 110 },
     { item_id: 103, quantity: 3, price: 5 },
     { item_id: 38, quantity: 2, price: 300 }
   ]
}
{
    _id: 2,
    items: [
       { item_id: 4, quantity: 1, price: 23 }
    ]
}

我该怎么办?

你只需要使用$size along with the $filter聚合运算符

db.collection.aggregate([
  { '$match': { '_id': 1 }},
  { '$project': {
    'counts': {
      '$size': {
        '$filter': {
          'input': '$items',
          'cond': { '$eq': ['$$this.quantity', 3] }
        }
      }
    }
  }}
])

MongoPlayground

可以使用mongodb的$size聚合函数得到需要的结果