Introduction to MongoDB $exists Operator

$exists is a query operator in MongoDB that is used to determine whether a specified field exists in a document. This operator returns all documents that either have or do not have the specified field. If the specified field does not exist, all documents that are missing that field will be returned, and if the specified field exists, all documents containing that field will be returned.

Syntax

The syntax for the $exists operator is as follows:

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

Here, field represents the name of the specified field, and <boolean> is a boolean value that specifies whether the field exists, with a value of either true or false.

Use Cases

The $exists operator is commonly used to query specific documents, such as whether a certain field exists or not. For example, if we want to query all documents in a users collection that have an email field, we can use the following query:

db.users.find({ email: { $exists: true } })

Examples

The following examples demonstrate how to use the $exists operator to query documents that contain or do not contain a specified field.

Example Data

Assuming we have a collection named products that contains the following documents:

{ "_id" : 1, "name" : "Product A", "description": "Description A" }
{ "_id" : 2, "name" : "Product B", "price": 10.99 }
{ "_id" : 3, "name" : "Product C", "price": 8.99, "quantity": 20 }

Example Queries

  1. Query all documents that contain the description field:

    db.products.find({ description: { $exists: true } })
    

    Result:

    { "_id" : 1, "name" : "Product A", "description": "Description A" }
  2. Query all documents that do not contain the quantity field:

    db.products.find({ quantity: { $exists: false } })
    

    Result:

    { "_id" : 1, "name" : "Product A", "description": "Description A" }
    { "_id" : 2, "name" : "Product B", "price": 10.99 }

Conclusion

The $exists operator is a query operator used to determine whether a specified field exists in a document. It can be used to query documents that contain or do not contain a specified field. This operator is very useful and can greatly improve the efficiency of queries.