0

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"
     }
   ]
 }
]

1 Answer 1

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.