Indraraj26
Indraraj26

Reputation: 1966

count based on nested key mongodb

How can i count based on xTag key is on doc I tried this but it does not provide me actual count

db.collection.find({
  "products.xTag": {
    $exists: false
  }
}).count();

when you run with $exist:true i would expect result 1

When you run with $exist:false i would expect result 3

Playground: https://mongoplayground.net/p/_gf7RzGc8oB

Structure:

[
 {
   "item": 1,
   "products": [
     {
       "name": "xyz",
       "xTag": 32423
     },
     {
       "name": "abc"
     }
   ]
 },
 {
   "item": 2,
   "products": [
     {
       "name": "bob",
       
     },
     {
       "name": "foo"
     }
   ]
 }
]

Upvotes: 0

Views: 53

Answers (1)

turivishal
turivishal

Reputation: 36104

It is not possible with find(), You can use aggregate(),

  • $unwind deconstruct products array
  • $match your condition
  • $count total documents
db.collection.aggregate([
  { $unwind: "$products" },
  { $match: { "products.xTag": { $exists: false } } },
  { $count: "count" }
])

Playground

Upvotes: 1

Related Questions