Persistence top

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE

1. Overview

In this short tutorial, we'll see how to check field existence in MongoDB. 

First, we'll create a simple Mongo database and sample collection. Then, we'll put dummy data in it to use later in our examples. After that, we'll show how to check whether the field exists or not in a native Mongo query as well as in Java.

2. Example Configuration

Before we start checking field existence, we need an existing database, collection, and dummy data for later use. We'll be using Mongo shell for that.

Firstly, let's switch Mongo shell context to an existence database:

use existence

It's worth pointing out that MongoDB only creates the database when you first store data in that database. We'll insert a single user into the users collection:

db.users.insert({name: "Ben", surname: "Big" })

Now we have everything we need to check, whether the field exists or not.

3. Checking Field Existence in Mongo Shell

Sometimes we need to check for specific field existence by using a basic query, e.g., in Mongo Shell or any other database console. Luckily for us, Mongo provides a special query operator, $exists, for that purpose:

db.users.find({ 'name' : { '$exists' : true }})

We use a standard find Mongo method in which we specify the field we are looking for and use the $exists query operator. If the name field exists in the users collection, all rows containing that field will be returned:

[
  {
    "_id": {"$oid": "6115ad91c4999031f8e6f582"},
    "name": "Ben",
    "surname": "Big"
  }
]

If the field is missing, we'll get an empty result.

4. Checking Field Existence in Java

Before we go through possible ways to check field existence in Java, let's add the necessary Mongo dependency to our project. Here's the Maven dependency:

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.12.10</version>
</dependency>

And here's the Gradle version:

implementation group: 'org.mongodb', name: 'mongo-java-driver', version: '3.12.10'

Finally, let's connect to the existence database and the users collection:

MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("existence");
MongoCollection<Document> collection = db.getCollection("users");

4.1. Using Filters

The com.mongodb.client.model.Filters is a util class from the Mongo dependency that contains a lot of useful methods. We're going to use the exists() method in our example:

Document nameDoc = collection.find(Filters.exists("name")).first();
assertNotNull(nameDoc);
assertFalse(nameDoc.isEmpty());

First, we try to find elements from the users collection and get the first found element. If the specified field exists, we get a nameDoc Document as a response. It's not null and not empty.

Now, let's see what happens when we try to find a non-existing field:

Document nameDoc = collection.find(Filters.exists("non_existing")).first();
assertNull(nameDoc);

If no element is found, we get a null Document as a response.

4.2. Using a Document Query

The com.mongodb.client.model.Filters class isn't the only way to check field existence. We can use an instance of com.mongodb.BasicDBObject:

Document query = new Document("name", new BasicDBObject("$exists", true));
Document doc = collection.find(query).first();
assertNotNull(doc);
assertFalse(doc.isEmpty());

The behavior is the same as in the previous example. If the element is found, we receive a not null Document, which is empty.

The code behaves the same also in a situation when we try to find a non-existing field:

Document query = new Document("non_existing", new BasicDBObject("$exists", true));
Document doc = collection.find(query).first();
assertNull(doc);

If no element is found, we get a null Document as a response.

5. Conclusion

In this article, we discussed how to check field existence in MongoDB. Firstly, we showed how to create a Mongo database, collection, and how to insert dummy data. Then, we explained how to check whether a field exists or not in Mongo shell using a basic query. Finally, we explained how to check field existence using the com.mongodb.client.model.Filters and a Document query approach.

As always, the full source code of the article is available over on GitHub.

Persistence bottom
Get started with Spring Data JPA through the reference Learn Spring Data JPA course: >> CHECK OUT THE COURSE
Persistence footer banner
guest
0 Comments
Inline Feedbacks
View all comments