Skip to content

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.


$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.


 { field: { $exists: <boolean> } }


I want to retrieve all documents from users collection that have status field present.

let users = await mongo.getdbDriverConnection()
            .find({ status: { $exists: true} });

We can combine other filters with $exists like..

let activeUsers = await mongo.getdbDriverConnection()
            .find({ status: { $exists: true}, , $nin: [ "Available", "Busy" ] });
See also  Rename a collection in MongoDB

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.