Astora
Astora

Reputation: 725

How to return only the documents that contain the specified field in the query

For example, I have the query:

db.person.find({$and:[{name: "Jack"},{married: {$not: {$eq: "no"}}}]})

The result is:

{ "_id" : ObjectId("5d2d199ddde29047871b5181"), "name" : "Jack", "age" : 20 }
{ "_id" : ObjectId("5d38cdf960b4663b4581ed5d"), "name" : "Jack", "age" : 19 }
{ "_id" : ObjectId("5d38ce1a60b4663b4581ed5e"), "name" : "Jack", "married" : "yes" }

How can I return only the line that have name and married like:

{ "_id" : ObjectId("5d38ce1a60b4663b4581ed5e"), "name" : "Jack", "married" : "yes" }

Upvotes: 1

Views: 35

Answers (1)

Ashh
Ashh

Reputation: 46481

You can use below query

db.collection.find({
  "name": "Jack",
  "married": { "$ne": "no", "$exists": true }
})

Actually You need to check for two condition for married field. One where it $exists and one where it is $ne to "no"

Upvotes: 1

Related Questions