简体   繁体   中英

How to count objects in an array in mongodb?

I want to count objects whose quantity is 3 in an array in the document whose _id is 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 }
    ]
}

What should I do?

You just need to use $size along with the $filter aggregation operator

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

MongoPlayground

您可以使用mongodb的$ size聚合函数并获得所需的结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM