Search for document that has field using $exists in MongoDB

Search for document that has field using $exists in MongoDB

$exists operator matches documents that have the specified field. For example you want to select all the documents that have the field name.

The $exists operator takes a boolean, so it have only two values either true (exists) or false (not having that field).

Inserting Documents

{ name: "article 1" },
{ "nbr": 5},
{ name: "article 2"}

Search for document containing the value using $exists

db.articles.find({ name: {$exists: true }})


{ "_id" : ObjectId("5e31cd67f098cf25b5b434dd"), "name" : "article 1" }
{ "_id" : ObjectId("5e31cd67f098cf25b5b434df"), "name" : "article 2" }