Home » Framework » Criteria Queries of MongoDB in Spring Boot Application

Criteria Queries of MongoDB in Spring Boot Application

This article explains how to use the criteria query to fetch the data from MongoDB with Spring Boot Application. There are lots of query operators available in MongoDB. In this article, let us see how to use those operators in the criteria query and some other querying methods of MongoDB.

The operators of MongoDB are classified as Query Selector (or) Query Operators, Projection Operators, and Miscellaneous Operators. The Query Operators are classified as Comparison, Logical, Element, Evaluation, Geospatial, Array, and Bitwise Operator.

In this article let us see how to use all the operators from Comparison and Logical in the Criteria Query.

Comparison Operators of MongoDB

There are many Comparison Operators are available in MongoDB. That are $eq, $ne, $gt, $gte, $lt, $lte, $in, and $nin.

Usage of $eq and $ne Operators

The operator $eq checks if the field value is equal or not. In Spring Boot Data MongoDB the operator $eq is not available instead $is operator does the same thing. Let us see the example below.

//List of records from user_profile collection
[
    {
        "_id": "60e3451066e0c711cd5cdf50",
        "firstName": "John",
        "lastName": "Paul",
        "age": 30,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER", "ADMIN"
        ]
    },
   {
        "_id": "60e3451066e0c711cd5cdf51",
        "firstName": "Nivin",
        "lastName": "Paul",
        "age": 35,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER"
        ]       
    },
   {
        "_id": "60e3451066e0c711cd5cdf52",
        "firstName": "Raja",
        "lastName": "Sekar",
        "age": 30,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "ADMIN"
        ]
   }
]

The above is the list of data of the "user_profile" collection of MongoDB that is serialized with the java entity ProfileVO. Please note we have to perform all the queries with the list of above data.

Query query = new Query();
query.addCriteria(Criteria.where("lastName").is("Paul"));
return mongoTemplate.find(query, ProfileVO.class);

The above query returns the list of records where the last name equals the name 'Paul'. Note that by default all the MongoDB queries are case sensitive. The output is below.

[
    {
        "_id": "60e3451066e0c711cd5cdf50",
        "firstName": "John",
        "lastName": "Paul",
        "age": 30,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER", "ADMIN"
        ]
    },
   {
        "_id": "60e3451066e0c711cd5cdf51",
        "firstName": "Nivin",
        "lastName": "Paul",
        "age": 35,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER"
        ]       
    }
]

The operator $ne checks if the field value is not equal or not. Let us see the example below.

Query query = new Query();
query.addCriteria(Criteria.where("lastName").ne("Paul"));
return mongoTemplate.find(query, ProfileVO.class);

The above query returns the list of records where the last name does not equals the name 'Paul'. The output is below.

[
  {
        "_id": "60e3451066e0c711cd5cdf52",
        "firstName": "Raja",
        "lastName": "Sekar",
        "age": 30,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "ADMIN"
        ]
   }
]

Usage of $gt and $gte Operators

The operator $gt checks whether the field value is greater than or not and the operator $gte checks whether the field value is greater than or equal or not. Let see the examples of both.

Query query = new Query();
query.addCriteria(Criteria.where("age").gt(30));
return mongoTemplate.find(query, ProfileVO.class);

The above query returns the list of records where the age is greater than 30. The output is below.

[
  {
        "_id": "60e3451066e0c711cd5cdf51",
        "firstName": "Nivin",
        "lastName": "Paul",
        "age": 35,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER"
        ]        
    }
]
Query query = new Query();
query.addCriteria(Criteria.where("age").gte(30));
return mongoTemplate.find(query, ProfileVO.class);

The above query returns the list of records where the age is greater than or equal to 30. The output is below.

[
    {
        "_id": "60e3451066e0c711cd5cdf50",
        "firstName": "John",
        "lastName": "Paul",
        "age": 30,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER", "ADMIN"
        ] 
    },
   {
        "_id": "60e3451066e0c711cd5cdf51",
        "firstName": "Nivin",
        "lastName": "Paul",
        "age": 35,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER"
        ]       
    },
   {
        "_id": "60e3451066e0c711cd5cdf52",
        "firstName": "Raja",
        "lastName": "Sekar",
        "age": 30,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "ADMIN"
        ] 
   }
]

Usage of $lt and $lte Operators

The operator $lt checks whether the field value is less than or not and the operator $lte checks whether the field value is less than or equal or not. I think no need for examples here, Hope you can test it on your own.

Usage of $in and $nin Operators

The operator $in checks whether the field value contains the specified value or not. Here the field contains the array of values. Let's see the example below.

Query query = new Query();
query.addCriteria(Criteria.where("roles").in("ADMIN"));
return mongoTemplate.find(query, ProfileVO.class);

The above query returns the list of records where the field 'roles' contains the specified value 'ADMIN'. The output is below.

[
    {
        "_id": "60e3451066e0c711cd5cdf50",
        "firstName": "John",
        "lastName": "Paul",
        "age": 30,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER", "ADMIN"
        ] 
    },  
   {
        "_id": "60e3451066e0c711cd5cdf52",
        "firstName": "Raja",
        "lastName": "Sekar",
        "age": 30,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "ADMIN"
        ] 
   }
]

The operator $nin checks whether the field value does not contain the specified value or not. Here the field contains the array of values. Let's see the example below.

Query query = new Query();
query.addCriteria(Criteria.where("roles").nin("ADMIN"));
return mongoTemplate.find(query, ProfileVO.class);

The above query returns the list of records where the field 'roles' does not contain the specified value 'ADMIN'. The output is below.

[
   {
        "_id": "60e3451066e0c711cd5cdf51",
        "firstName": "Nivin",
        "lastName": "Paul",
        "age": 35,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER"
        ]       
    }
]

I hope you understood the usage of Comparison Operators. Now let's see the logical operators.

Logical Operators of MongoDB

We can use Logical Operators to specify the logic based on our need with the criteria query. Many Operators are available that are $and, $not, $or, and $nor. Let's see one by one.

Usage of $and and $or Operators

The operator $and combines the multiple queries with the logical AND. For example, if we join two different logic of queries with $and operator then it returns the value when both the logic is true. Let's see the example below

Query query = new Query();
query.addCriteria(Criteria.where("firstName").is("Nivin").and("lastName").is("Paul"));		
return mongoTemplate.find(query, ProfileVO.class);

The another way of writing $and operator query is below.

Criteria criteria = new Criteria();		
criteria.andOperator(Criteria.where("firstName").is("Nivin"),Criteria.where("lastName").is("Paul"));
Query query = new Query();
query.addCriteria(criteria);		
return mongoTemplate.find(query, ProfileVO.class);

The above two formats of queries with $and operator return the list of records where the field 'firstName' matches with 'Nivin' and the field 'lastName' matches with 'Paul'. The output is below.

[
   {
        "_id": "60e3451066e0c711cd5cdf51",
        "firstName": "Nivin",
        "lastName": "Paul",
        "age": 35,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER"
        ]       
    }
]

The $or operator also joins multiple criteria queries of different logic with logical OR. It returns the list of records if any one of the logic is true. The below query returns the list of records where the 'firstName' matches with 'Nivin' or the 'lastName' matches with 'Sekar'.

Criteria criteria = new Criteria();		
criteria.orOperator(Criteria.where("firstName").is("Nivin"),Criteria.where("lastName").is("Sekar"));
Query query = new Query();
query.addCriteria(criteria);		
return mongoTemplate.find(query, ProfileVO.class);
[
    {
        "_id": "60e3451066e0c711cd5cdf51",
        "firstName": "Nivin",
        "lastName": "Paul",
        "age": 35,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER"
        ]       
    },
   {
        "_id": "60e3451066e0c711cd5cdf52",
        "firstName": "Raja",
        "lastName": "Sekar",
        "age": 30,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "ADMIN"
        ] 
   }
]

Usage of $nor and $not Operators

The operator $nor combines multiple criteria queries of different logic with logical NOR. It returns the list of records if all the logic fails. The example is below.

Criteria criteria = new Criteria();		
criteria.norOperator(Criteria.where("firstName").is("Nivin"),Criteria.where("lastName").is("Sekar"));
Query query = new Query();
query.addCriteria(criteria);		
return mongoTemplate.find(query, ProfileVO.class);

The above query returns the list of records where the field 'firstName' does not match with 'Nivin' and the field 'lastName' does not match with 'Sekar'. The output is below.

[
    {
        "_id": "60e3451066e0c711cd5cdf50",
        "firstName": "John",
        "lastName": "Paul",
        "age": 30,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER", "ADMIN"
        ] 
    }
]

In Spring Data MongoDB there is no $not operator instead we can use the $ne operator. Both are doing the same work. I hope you understood how to use the logical operators with criteria query in Spring Boot Application.

Now let us see some more default methods of MongoTemplate for querying the MonfoDB.

Save or Insert

Save or Insert insert the new record into the collection of MongoDB. The example for both is below.

    {
        "firstName": "Salman",
        "lastName": "Khan",
        "age": 30,
        "roles": [
            "USER", "ADMIN"
        ] 
    }
mongoTemplate.save(userVO); (or) 
mongoTemplate.insert(profileVO);

The above methods save the above record into the collection of MongoDB. if we want to save multiple records then we can use the below example with insertAll() function of MongoTemplate.

//1rst record
ProfileVO profileVO = new ProfileVO();
profileVO.setFirstName("Raja");
profileVO.setLastName("Sekar");
//2nd record			
ProfileVO profileVO1 = new ProfileVO();
profileVO1.setFirstName("Kalam");
profileVO1.setLastName("khan");
//list of records		
List<ProfileVO> profileList = new ArrayList<ProfileVO>();
profileList.add(profileVO);
profileList.add(profileVO1);
mongoTemplate.insertAll(profileList

upsert, updateFirst, and updateMulti

The method upsert updates the record that matches with the query or inserts the new record if that does not match with the query. The below query does that.

//criteria query
Query query = new Query();	
query.addCriteria(Criteria.where("firstName").is("Nivin"));
//update definition		
Update updateDef = new Update();
updateDef.set("lastName", "Nivin Pual");
mongoTemplate.upsert(query, updateDef, ProfileVO.class);

The method updateFirst updates the first record based on the insertion order and based on the query. Even if the query matches with multiple records it updates the first matching record only. The method updateMulti updates the multiple records that match the query. The below query does both.

//criteria query
Query query = new Query();	
query.addCriteria(Criteria.where("firstName").is("Nivin"));
//update definition		
Update updateDef = new Update();
updateDef.set("lastName", "Nivin Pual");
//update the first matching record
mongoTemplate.upsertFirst(query, updateDef, ProfileVO.class);
//update the multiple matching records
mongoTemplate.updateMulti(query, updateDef, ProfileVO.class);

Count, Skip, and Limit

The method count returns the records count of a collection based on the query we write in it. It returns the count as a long type. The method skip skips the record based on the number we specify in it and returns the records based on the query.

The method limit limits the fetching records. For example, if we give any number inside the limit method then it fetches only that number of records. The below snippet is the example for all.

Query query = new Query();	
query.addCriteria(Criteria.where("age").gt(30));				
return mongoTemplate.count(query, ProfileVO.class);

The above query returns the count of records where the age is greater than 30. It returns the output as 1.

Query query = new Query();	
query.addCriteria(Criteria.where("age").gt(10));
query.skip(1);
query.limit(1);
return mongoTemplate.find(query, ProfileVO.class);

The above query returns only one record based on the limit and skips the one record based on the insertion order and that matches the criteria. The output for the above query is below.

  {
        "_id": "60e3451066e0c711cd5cdf51",
        "firstName": "Nivin",
        "lastName": "Paul",
        "age": 35,
        "_class": "com.tipstocode.model.ProfileVO",
        "roles": [
            "USER"
        ]       
  }

I hope you understood all the criteria queries with different logic using different operators and some basic methods for querying MongoDB. Some more querying methods are available in the articles that are Basic Crud Operation with MongoDB and Different types of find queries in MongoDB.

Leave a Reply

Your email address will not be published. Required fields are marked *