MongoDB

MongoDB $Exists Query

The MongoDB $exists operator permits the user to obtain the documents from a collection irrespective of whether a relevant field is present or not. The $exists operator only takes the Boolean parameter which can be true or false. The specified true value to the $exists operator returns the matched document that includes the specified field even where the field value is null. On the other hand, the documents that don’t include the specified field are returned when the value of the $exists value is set to false.

How Does the $Exists Operator Work in MongoDB?

The $exists operator is used in the specified field name. The field name is defined in the find() method. Then, the specified field name is further set as the expression of the $exists operator. The following syntax is provided for better understanding:

db.collection.find(field_name:{$exist: Boolean_value}).

Before beginning the usage of the $exists operator, it is required to establish the MongoDB collection and retrieve the content of that collection, which will be used by the $exists operator. We use the “Customer” collection for the $exists operator and insert the following document inside that collection using the insertMany() method.

db.Customer.insertMany([

  {

    "OrderName": "StoryBooks",

    "QTY": 3,

    "Price": 600,

    "Date": "24-11-2022",

    "Details" : [{"name":"kyle"}, {"age": 21}, {"phone": 032367}]

 

  },

  {

    "OrderName": "Perfume",

    "QTY": 1,

    "Price": 450,

    "Date": "24-11-2022",

    "Details" : [{"name":"Richard"}, {"age": 28}, {"phone": "8237818"}]

  },

  {

    "OrderName": "Watch",

    "QTY": 1,

    "Price": 750,

    "Details" : [{"name":"Addy"}, {"age": 34}, {"phone": 419230}],

 

  },

  {

    "OrderName": "Bracelet",

    "QTY": 2,

    "Price": 590,

    "Date": "2-11-2022",

    "Details" : [{"name":"Emily"}, {"age": 19}, {"phone": 2304949}]

   }

])

When the document is inserted properly into the collection, we get the following output from the MongoDB shell:

Example 1: Using the MongoDB $Exists Operator with True Value

When the $exists operator of MongoDB is assigned with the “true” Boolean value, it returns all the documents of the specified collection having that field name. There, we have a query using the $exists operator where we first specify the “OrderName” field name. The “OrderName” field is set with the {$exists : true } expression where the $exits operator is set with the “true” value. The $exits operator here identifies the document which contains the “OrderName” field in the collection.

db.Customer.find({"OrderName" : { $exists : true } } ).pretty();

The “OrderName” field exists in all the documents of the “Customer” collection which is returned after executing the query.

Example 2:  Using the MongoDB $Exists Operator with a False Value

When the $exists operator is associated with the “false” value, it returns those documents which contain the given field. Now, we implement the query of the $exists operator with the false value. We first specify the “Date” field. Then, we set the $exists operator which is equal to the “false” value. The $exists operator searches for that document where the “Date” field is not included as the “false” value is set against it.

db.Customer.find({"Date" : { $exists : false } } ).pretty();

When the query of the $exists operator is run on the shell, it returns one document with the non-existence “Date” field.

Example 3: Using the MongoDB $Exists Operator with the Conditional Operator 

This is an example of the $exists operator which is employed with the “gt” comparison operator. The query is given where we have a “price” field name to be identified by the $exists operator and those “price” field values are only returned according to the comparison statement. The “price” field is set with the double expression. The first expression is the “$exists: true” to return the document which is associated with the “price” field. Then, the second expression is the “$gt: 550” which indicates those retrieved documents whose price value is greater than the “550” value.

db.Customer.find({Price: {$exists: true, $gt: 550}}).pretty()

The documents are fetched as an output which contains the “price” field and the “price” values are greater than “550”.

Example 4: Using the MongoDB $Exists Operator for Multiple Fields 

As we use the $exist operator for the single field to be identified, we use the $exists operator here for the multiple fields to be retrieved from the document. Inside the following query, we specify the “QTY” field which is set with the $exist operator with the true value. The “Details” field is also defined which is also provided with the $exist operator and the value against it is also true. Note that we set the $exist operator separately for each specified field.

db.Customer.find( {

 QTY: { $exists: true },

 Details: { $exists: true }

} )

The $exists operator returns those documents in the following output which contains the “QTY” and “Details” fields.

Example 5: Using the MongoDB $Exists Operator for the Array Field 

Here, we determine whether or not a field exists in the given array of the document. Notice the following query. We define the array field as “Details.age” where “Details” is the array of the document and the field element is the “age”. The $exists operator is then implemented with the “true” Boolean value which finds the existence of the “age” field from the “Details” array of the document.

db.Customer.find({"Details.age":{$exists:true}})

The output displays the documents that include the “age” array field.

Example 6: Using the MongoDB $Exists Operator with $Nin Operator

We use the $exists method with the comparison operator in the earlier example. We can also use this operator with another operator just like the $nin operator. First, the $exists retrieves the documents depending on the given field. Then, $nin generates the documents that do not include the given values. Let’s have the following query of the $exists operator along with the $nin operator. We give a “Date” field where the $exists operator is utilized with the “true” value. Then, the value of the “Date” field is then defined with the $nin operator. The $exists operator checks the existence of the “Date” field and the $nin operator excludes the document which is retrieved from the $exists operator whose value is “24-11-2022”.

db.Customer.find( {Date : { $exists: true, $nin: ["24-11-2022"] } } )

The working of the $exists and the $nin operators which retrieve the document from the collection is in the following image:

Conclusion

The $exists operator is very useful when we want to find the existence of a particular document in our collection. We can even include the specific document or exclude it to be displayed in the MongoDB collection. We provided the use cases of the $exists operator to demonstrate the functionality of this operator in MongoDB. We examined the existence of embedded documents using the $exists operator. Furthermore, we used the $exists operator with the comparison and $nin operators. Each of these operators has a different working with the $exists operator.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.