How can I check whether a field exists or not in MongoDB?

Or you can use:

import static com.mongodb.client.model.Filters.exists;

Document doc = (Document) mongoCollection.find(exists("otherInfo")).first();

You can use the $exists operator in combination with the . notation. The bare query in the mongo-shell should look like this:

db.yourcollection.find({ 'otherInfo.text' : { '$exists' : true }})

And a test case in Java could look like this:

    BasicDBObject dbo = new BasicDBObject();
    dbo.put("name", "first");
    collection.insert(dbo);

    dbo.put("_id", null);
    dbo.put("name", "second");
    dbo.put("otherInfo", new BasicDBObject("text", "sometext"));
    collection.insert(dbo);

    DBObject query = new BasicDBObject("otherInfo.text", new BasicDBObject("$exists", true));
    DBCursor result = collection.find(query);
    System.out.println(result.size());
    System.out.println(result.iterator().next());

Output:

1
{ "_id" : { "$oid" : "4f809e72764d280cf6ee6099"} , "name" : "second" , "otherInfo" : { "text" : "sometext"}}

You can use the com.mongodb.QueryBuilder class to build a query provided in Matt's answer:

QueryBuilder queryBuilder = QueryBuilder.start("otherInfo.text").exists(true);
DBObject query = queryBuilder.get();
DBCursor dbCursor = collection.find(query);

Tags:

Java

Mongodb