Check If a Field Exists in MongoDB

If you want to check if a field exists in a collection or filter out documents based on a certain field for either including or excluding them, you can use the $exists operator. Let’s quickly learn about it.

MongoDB $exists Operator

The $exists operator allows us to check the existence of a field in MongoDB documents. It accepts a boolean value for querying. If the boolean value is true, it will return the document that contains the given field, including those where the field value is null. If the boolean value is false, it will only return documents that do not contain the specified field.

Syntax:

db.collection.find({ field: { $exists: boolean} })

Parameters:

  • collection: The name of the collection in which we are searching for documents.
  • find: The method used to perform the query on the documents.
  • field: The name of the field within the documents that we are querying for. This specifies which field’s existence is being checked.
  • boolean: It can be true or false.

Returns:

When the boolean value is true, it returns only those documents where the specified field exists. When it’s false, it returns all documents excluding those where the specified field exists.

We have already covered the find() and findOne() methods in a separate tutorial. Be sure to check it out!

Finding Documents Including Specific Fields

Let’s use the $exists operator and set the boolean value to true to check if some specific fields exist in the document.

First, choose a database to get started with:

show dbs
use droneStore

Below are the documents in this database collection:

> db.drones.find({}).pretty()

{
        "_id" : ObjectId("603502ba24df1c2350e676e9"),
        "utility" : [
                "Delivery"
        ],
        "onSale" : false,
        "name" : "RX - Ferezza S120",
        "price" : 105499,
        "weight" : "26 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("60352ecb6ce2811cc8892a75"),
        "utility" : [
                "Monitoring or Inspection"
        ],
        "onSale" : false,
        "name" : "SV - LaserX AW205",
        "price" : 4000,
        "__v" : 0
}
{
        "_id" : ObjectId("6157239d341d653bccaf7822"),
        "utility" : [
                "Recreation"
        ],
        "onSale" : false,
        "name" : "DF - Jetfire Nitro RX-V",
        "price" : 22000,
        "weight" : "3 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("6157240c341d653bccaf7823"),
        "utility" : [
                "Monitoring or Inspection"
        ],
        "onSale" : false,
        "name" : "Pink Sentinel Q95",
        "price" : 13000,
        "__v" : 0
}
{
        "_id" : ObjectId("61573885341d653bccaf7825"),
        "utility" : [
                "Security"
        ],
        "onSale" : false,
        "name" : "SV - Xorvia 9908Y",
        "price" : 7760,
        "weight" : "3.8 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("615738d6341d653bccaf7826"),
        "utility" : [
                "Photography"
        ],
        "onSale" : false,
        "name" : "SV - Ryee SW657",
        "price" : 8900,
        "weight" : "760 grams",
        "__v" : 0
}
{
        "_id" : ObjectId("61573946341d653bccaf7827"),
        "utility" : [
                "Monitoring or Inspection"
        ],
        "onSale" : false,
        "name" : "RV - Zereca Eagle-i",
        "price" : 3200,
        "__v" : 0
}
{
        "_id" : ObjectId("615739bb341d653bccaf7828"),
        "utility" : [
                "Delivery"
        ],
        "onSale" : false,
        "name" : "OS - Falcon GO!",
        "price" : 45000,
        "weight" : "17 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61589f092d0a441e040c3fdc"),
        "utility" : [
                "Photography"
        ],
        "onSale" : false,
        "name" : "DX - Firebird Scarlet Red",
        "price" : 45000,
        "weight" : "4.7 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61589f6e2d0a441e040c3fdd"),
        "utility" : [
                "Photography"
        ],
        "onSale" : false,
        "name" : "IJ - Optico X53",
        "price" : 3900,
        "__v" : 0
}

The pretty() function in MongoDB can format the query results with a proper indentation and produce readable output, click here to learn more about it.

You can see that not every document has a “weight” field.

Let’s use $exists to only get those documents that have the “weight” field:

> db.drones.find( { weight: { $exists: true } } ).pretty()

{
        "_id" : ObjectId("603502ba24df1c2350e676e9"),
        "utility" : [
                "Delivery"
        ],
        "onSale" : false,
        "name" : "RX - Ferezza S120",
        "price" : 105499,
        "weight" : "26 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("6157239d341d653bccaf7822"),
        "utility" : [
                "Recreation"
        ],
        "onSale" : false,
        "name" : "DF - Jetfire Nitro RX-V",
        "price" : 22000,
        "weight" : "3 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61573885341d653bccaf7825"),
        "utility" : [
                "Security"
        ],
        "onSale" : false,
        "name" : "SV - Xorvia 9908Y",
        "price" : 7760,
        "weight" : "3.8 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("615738d6341d653bccaf7826"),
        "utility" : [
                "Photography"
        ],
        "onSale" : false,
        "name" : "SV - Ryee SW657",
        "price" : 8900,
        "weight" : "760 grams",
        "__v" : 0
}
{
        "_id" : ObjectId("615739bb341d653bccaf7828"),
        "utility" : [
                "Delivery"
        ],
        "onSale" : false,
        "name" : "OS - Falcon GO!",
        "price" : 45000,
        "weight" : "17 kilograms",
        "__v" : 0
}
{
        "_id" : ObjectId("61589f092d0a441e040c3fdc"),
        "utility" : [
                "Photography"
        ],
        "onSale" : false,
        "name" : "DX - Firebird Scarlet Red",
        "price" : 45000,
        "weight" : "4.7 kilograms",
        "__v" : 0
}

See, we successfully found six documents that have the “weight” field with the help of the $exists operator.

Finding Documents Excluding Specific Fields

Now, let’s use the $exists operator for the same “weight” field and set the boolean value to false:

> db.drones.find( { weight: { $exists: false } } ).pretty()

{
        "_id" : ObjectId("60352ecb6ce2811cc8892a75"),
        "utility" : [
                "Monitoring or Inspection"
        ],
        "onSale" : false,
        "name" : "SV - LaserX AW205",
        "price" : 4000,
        "__v" : 0
}
{
        "_id" : ObjectId("6157240c341d653bccaf7823"),
        "utility" : [
                "Monitoring or Inspection"
        ],
        "onSale" : false,
        "name" : "Pink Sentinel Q95",
        "price" : 13000,
        "__v" : 0
}
{
        "_id" : ObjectId("61573946341d653bccaf7827"),
        "utility" : [
                "Monitoring or Inspection"
        ],
        "onSale" : false,
        "name" : "RV - Zereca Eagle-i",
        "price" : 3200,
        "__v" : 0
}
{
        "_id" : ObjectId("61589f6e2d0a441e040c3fdd"),
        "utility" : [
                "Photography"
        ],
        "onSale" : false,
        "name" : "IJ - Optico X53",
        "price" : 3900,
        "__v" : 0
}

The return document does not have the “weight” field.

Conclusion

In short, the $exists operator is used to check for the existence of fields in a set of documents. It takes a boolean value as a parameter which if true $exists matches the documents where the field exists and if false, it excludes documents where the field exists. This is useful in lots of real-life scenarios like selecting students whose fees are paid or getting a list of users whose subscriptions have not been renewed, etc. This operator is also useful for querying for null or missing fields.

Reference

https://www.mongodb.com/docs/manual/reference/operator/query/exists/#mongodb-query-op.-exists

Aneesha S
Aneesha S
Articles: 171