This checks the document for the existence of the fields in the specified collection.
The syntax is
{ field: { $exists: <boolean> } }
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.
>db.car.find({ regno:{ $exists:true}})
{ "_id" : 51, "name" : "NissanSunny", "cno" : "H678", "regno" : 141, "speed" : 25 }
{ "_id" : 52, "name" : "Fiat", "cno" : "H679", "regno" : 142, "speed" : 57 }
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.
>db.car.find({ speed:{ $exists:true , $gt:80 }})
{ "_id" : ObjectId("5474896b93f400069d439c04"), "name" : "Micra", "color" : "Lime", "cno" : "H186", "mfdcountry" : "Ethopia", "speed" : 84 }
{ "_id" : ObjectId("5474896b93f400069d439c03"), "name" : "Palio", "color" : "Purple", "cno" : "H183", "mfdcountry" : "Venice", "speed" : 82 }
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.
>db.car.find( { mfdcountry: { $exists:false}})
{ "_id" : 8, "name" : "Zen", "speed" : 54 }
{ "_id" : ObjectId("5474896b93f400069d439c00"), "name" : "Indica", "color" : "Silver", "cno" : "H154" }
{ "_id" : 43, "name" : "Astar", "speed" : 79 }
{ "_id" : 51, "name" : "NissanSunny", "cno" : "H678", "regno" : 141, "speed" : 25 }
{ "_id" : 52, "name" : "Fiat", "cno" : "H679", "regno" : 142, "speed" : 57 }
{ "_id" : 59, "name" : "Quanta-45", "cno" : null, "regno" : null, "speed" : null }
{ "_id" : 99, "name" : "Brio", "cno" : null, "regno" : null, "speed" : null }
Retrieve documents having null values
This retrieves the documents that contains the null values for the field specified in the query.
>db.car.find( { speed: { $exists:true } })
{ "_id" : 8, "name" : "Zen", "speed" : 54 }
{ "_id" : 6, "name" : "HondaCity", "color" : "Grey", "cno" : "H106", "mfdcountry" : "Sweden", "speed" : 45 }
{ "_id" : ObjectId("5474642dd785e3a05a1808a7"), "name" : "Punto", "color" : "Wine Red", "cno" : "H109", "mfdcountry" : "Paris", "speed" : 45 }
{ "_id" : 9, "name" : "SwiftDezire", "color" : "Maroon", "cno" : "H108", "mfdcountry" : "New York", "speed" : 40 }
{ "_id" : 51, "name" : "NissanSunny", "cno" : "H678", "regno" : 141, "speed" : 25 }
{ "_id" : 99, "name" : "Brio", "cno" : null, "regno" : null, "speed" : null }
{ "_id" : 59, "name" : "Quanta-45", "cno" : null, "regno" : null, "speed" : null }
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.
package com.journaldev.mongodb;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import java.net.UnknownHostException;
public class MongoDBExists {
// method to check whether the field exists
public static void existstrue() throws UnknownHostException {
// Get a db connection
MongoClient m1 = new MongoClient("localhost");
// connect to test db,use your own here
DB db = m1.getDB("test");
// obtain the car collection
DBCollection coll = db.getCollection("car");
// checking whether regno field exists by setting exists to true
DBObject query = new BasicDBObject("regno", new BasicDBObject(
"$exists", true));
// store the documents in cursor car
DBCursor car = coll.find(query);
// iterate and print the contents of cursor
try {
while (car.hasNext()) {
System.out.println(car.next());
}
} finally {
// close the cursor
car.close();
}
}
// method to check the fields along along with the criteria entered
public static void existstruewithcriteria() throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB db = m1.getDB("test");
DBCollection coll = db.getCollection("car");
// check whether speed fields exists and speed greater than 80
DBObject query = new BasicDBObject("speed", new BasicDBObject(
"$exists", true).append("$gt", 80));
DBCursor car = coll.find(query);
System.out.println("-----------------------------------");
try {
while (car.hasNext()) {
System.out.println(car.next());
}
} finally {
car.close();
}
}
// method to check the field does not exist
public static void existsfalse() throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB db = m1.getDB("test");
DBCollection coll = db.getCollection("car");
// checking for mfdcountry field by setting exists to false
DBObject query = new BasicDBObject("mfdcountry", new BasicDBObject(
"$exists", false));
DBCursor car = coll.find(query);
System.out.println("-------------------------------------------------");
try {
while (car.hasNext()) {
System.out.println(car.next());
}
} finally {
car.close();
}
}
public static void existstruewithnullvalues() throws UnknownHostException {
MongoClient m1 = new MongoClient("localhost");
DB db = m1.getDB("test");
DBCollection coll = db.getCollection("car");
// returns documents with null values
DBObject query = new BasicDBObject("regno", new BasicDBObject(
"$exists", true));
DBCursor car = coll.find(query);
System.out.println("---------------------------------------------");
try {
while (car.hasNext()) {
System.out.println(car.next());
}
} finally {
car.close();
}
}
public static void main(String[] args) throws UnknownHostException {
// invoking all the methods
existstrue();
existstruewithcriteria();
existsfalse();
existstruewithnullvalues();
}
}
Output of the above program is:
{ "_id" : 51.0 , "name" : "NissanSunny" , "cno" : "H678" , "regno" : 141.0 , "speed" : 25.0}
{ "_id" : 52.0 , "name" : "Fiat" , "cno" : "H679" , "regno" : 142.0 , "speed" : 57.0}
--------------------------------------------------------------------------------------------------------------
{ "_id" : { "$oid" : "5474896b93f400069d439c04"} , "name" : "Micra" , "color" : "Lime" , "cno" : "H186" , "mfdcountry" : "Ethopia" , "speed" : 84}
{ "_id" : { "$oid" : "5474896b93f400069d439c03"} , "name" : "Palio" , "color" : "Purple" , "cno" : "H183" , "mfdcountry" : "Venice" , "speed" : 82}
------------------------------------------------------------------------------------------------------------------
{ "_id" : 8.0 , "name" : "Zen" , "speed" : 54.0}
{ "_id" : { "$oid" : "5474896b93f400069d439c00"} , "name" : "Indica" , "color" : "Silver" , "cno" : "H154"}
{ "_id" : 43 , "name" : "Astar" , "speed" : 79}
{ "_id" : 51.0 , "name" : "NissanSunny" , "cno" : "H678" , "regno" : 141.0 , "speed" : 25.0}
{ "_id" : 52.0 , "name" : "Fiat" , "cno" : "H679" , "regno" : 142.0 , "speed" : 57.0}
---------------------------------------------------------------------------------------------------------------
{ "_id" : 51.0 , "name" : "NissanSunny" , "cno" : "H678" , "regno" : 141.0 , "speed" : 25.0}
{ "_id" : 52.0 , "name" : "Fiat" , "cno" : "H679" , "regno" : 142.0 , "speed" : 57.0}
{ "_id" : 59.0 , "name" : "Quanta-45" , "cno" : null , "regno" : null , "speed" : null }
{ "_id" : 99.0 , "name" : "Brio" , "cno" : null , "regno" : null , "speed" : null }
MongoDB exists is a simple operation to understand and it can help us in selecting only specific documents that have the given field.