How to check if a field exists in a MongoDB document?
In this quick post, learn how to find out if a field has a value, any value in a document in MongoDB. To do this, we can use $exists operator in MongoDB.
Advertisements
$exists is a MongoDB operator that matches the documents and checks if the document has the field, including documents where the field value is null
. If <boolean>
is false, the query returns only the documents that do not contain the field. It basically checks if the field is present in a document, irrespective of the value.
Syntax
{ field: { $exists: <boolean> } }
Advertisements
Example
I want to retrieve all documents from users collection that have status field present.
let users = await mongo.getdbDriverConnection() .collection("users") .find({ status: { $exists: true} });
Advertisements
We can combine other filters with $exists like..
let activeUsers = await mongo.getdbDriverConnection() .collection("users") .find({ status: { $exists: true}, , $nin: [ "Available", "Busy" ] });