MongoDB exists example using Mongo Shell and Java Driver

This checks the document for the existence of the fields in the specified collection.

The syntax is

The operator accepts the boolean values of either true or false.

If the boolean value is set to true, the exists operator matches the documents that contain the fields specified in the input parameters. If the boolean option is set to false the query returns the documents which do not contain the field.

Let’s check out the examples of usage of exists operator.

Exists operator set to true

This operation returns only the documents that contain the field specified in the query.

The documents having the regno field are fetched when exists is set to true.

Exists operator set to true and selection criteria specified

This operation returns only the documents which satisfy the criteria entered and contain the fields specified in the query.

The documents having the speed field and the speed greater than 80 are retrieved from the collection.

Exists operator set to false

This retrieves the documents that do not contain the fields specified in the query.

Retrieve documents having null values

This retrieves the documents that contains the null values for the field specified in the query.

This operation retrieves the document having null values for speed field.

MongoDB Java Program for exists operations

Let’s now write a java program to check whether the fields exists in the MongoDB.

Output of the above program is:

MongoDB exists is a simple operation to understand and it can help us in selecting only specific documents that have the given field.

By admin

Leave a Reply

%d bloggers like this: