1

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

You can use $size aggregation function of mongodb and get the required result

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.