27

I am trying to find all documents that have this field, it doesn't matter what exact value it contains; I am only interested in the existence of it.

Here is an example:

{  
   "payload":{  
      "products":{  
         ...
      },
      "discount":{  
         "type":"1%",
         "value":"1",
         "name":"New Year Discount 1%"
      }
   }
}

I need to target any document that has a field with the name discount. How can I write a query to get such documents?

2 Answers 2

44

There's a $exists operator for that:

db.collectionName.find({"payload.discount": {$exists: true}})
Sign up to request clarification or add additional context in comments.

Comments

13

You're probably looking for the $exists operator:

db.collection.find({ "payload.discount": { $exists: true } })

Comments

Your Answer

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