Complete collection of methods to access mongodb using spring — spring data mongodb query Guide
1. General
Spring data mongodb is an artifact for the spring framework to access mongodb. It is very convenient to read and write Mongo libraries. This article introduces several methods of accessing mongodb database using spring data mongodb:
Before you start, you need to introduce Maven dependencies
1.1 add Maven dependency
If you want to use spring data mongodb, you need to add the following entries to your POM In the XML file:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.9.6.RELEASE</version>
</dependency>
Select the version as needed.
2. Document query
One of the most common ways to query mongodb using spring data is to use the query and criteria classes, which are very close to local operators.
2.1 is query
In the following example - we are looking for a user named Eric.
Let's take a look at our database:
[
{
"_id" : ObjectId("55c0e5e5511f0a164a581907"),"_class" : "org.baeldung.model.User","name" : "Eric","age" : 45
},{
"_id" : ObjectId("55c0e5e5511f0a164a581908"),"name" : "Antony","age" : 55
}
}]
Let's look at the query code:
Query query = new Query();
query.addCriteria(Criteria.where("name").is("Eric"));
List<User> users = mongoTemplate.find(query,User.class);
As expected, this logic returns:
{
"_id" : ObjectId("55c0e5e5511f0a164a581907"),"age" : 45
}
2.2 regular query
Regular expression is a more flexible and powerful query type. This uses a standard using mongodb $regex, which returns all records of the regular expression applicable to this field.
Its function is similar to the startingwith and endingwith operations - let's take a look at an example.
Find all users whose names begin with A. This is the status of the database:
[
{
"_id" : ObjectId("55c0e5e5511f0a164a581907"),"age" : 33
},{
"_id" : ObjectId("55c0e5e5511f0a164a581909"),"name" : "Alice","age" : 35
}
]
Let's create a query:
Query query = new Query();
query.addCriteria(Criteria.where("name").regex("^A"));
List<User> users = mongoTemplate.find(query,User.class);
This runs and returns 2 records:
[
{
"_id" : ObjectId("55c0e5e5511f0a164a581908"),"age" : 35
}
]
Here is another simple example. This time, find all users whose names end in C:
Query query = new Query();
query.addCriteria(Criteria.where("name").regex("c$"));
List<User> users = mongoTemplate.find(query,User.class);
So the result is:
{
"_id" : ObjectId("55c0e5e5511f0a164a581907"),"age" : 45
}
2.3 LT and GT
$LT (less than) operator and $GT (greater than).
Let's take a quick look at an example - we're looking for all users between the ages of 20 and 50.
The database is:
[
{
"_id" : ObjectId("55c0e5e5511f0a164a581907"),"age" : 55
}
}
Construction query:
Query query = new Query();
query.addCriteria(Criteria.where("age").lt(50).gt(20));
List<User> users = mongoTemplate.find(query,User.class);
Results - all users older than 20 and younger than 50:
{
"_id" : ObjectId("55c0e5e5511f0a164a581907"),"age" : 45
}
2.4 result sorting
Sort specifies the sort order of the results.
First - here is the existing data:
[
{
"_id" : ObjectId("55c0e5e5511f0a164a581907"),"age" : 35
}
]
After sorting:
Query query = new Query();
query.with(new Sort(Sort.Direction.ASC,"age"));
List<User> users = mongoTemplate.find(query,User.class);
This is the result of the query - well sorted by age:
[
{
"_id" : ObjectId("55c0e5e5511f0a164a581908"),"age" : 35
},{
"_id" : ObjectId("55c0e5e5511f0a164a581907"),"age" : 45
}
]
2.5 paging
Let's look at a simple example of using paging.
This is the status of the database:
[
{
"_id" : ObjectId("55c0e5e5511f0a164a581907"),"age" : 35
}
]
Now, the query logic only needs a page of size 2:
final Pageable pageableRequest = new PageRequest(0,2);
Query query = new Query();
query.with(pageableRequest);
result:
[
{
"_id" : ObjectId("55c0e5e5511f0a164a581907"),"age" : 33
}
]
To explore the full details of this API, here are the documents of the query and criteria classes.
3. Generated query methods
Generating query method is a feature of JPA and can also be used in spring data mongodb.
To achieve the 2-mile function, you only need to declare methods on the interface,
public interface UserRepository
extends MongoRepository<User,String>,QueryDslPredicateExecutor<User> {
...
}
3.1 FindByX
We'll simply start by exploring a query of type findby - in this case, find by name:
List<User> findByName(String name);
Same as in the previous Section 2.1 - the query will have the same results, finding all users with the given name:
List<User> users = userRepository.findByName("Eric");
3.2 StartingWith and endingWith.
Here is a simple example of the operation process:
List<User> findByNameStartingWith(String regexp);
List<User> findByNameEndingWith(String regexp);
The actual use of this example will of course be very simple:
List<User> users = userRepository.findByNameStartingWith("A");
List<User> users = userRepository.findByNameEndingWith("c");
The result is exactly the same.
3.3 Between
Similar to 2.3, this returns all users aged between agegt and agelt:
List<User> findByAgeBetween(int ageGT,int ageLT);
List<User> users = userRepository.findByAgeBetween(20,50);
3.4 like and orderby
Let's look at this more advanced example - combining two types of modifiers for the generated query.
We're going to find all users whose names contain the letter A, and we'll also sort the results in age order:
List<User> users = userRepository.findByNameLikeOrderByAgeAsc("A");
result:
[
{
"_id" : ObjectId("55c0e5e5511f0a164a581908"),"age" : 35
}
]
4. JSON query method
If we can't express the query by method name or condition, we can do something lower - use @ query annotation.
With this annotation, we can specify an original query - as a Mongo JSON query string.
4.1 FindBy
Let's start with a simple and see how we will be a method of finding types. First:
@Query("{ 'name' : ?0 }")
List<User> findUsersByName(String name);
Should this method return user placeholder by name? 0 refers to the first parameter of the method.
4.2 $regex
Let's look at a regular expression driven query - which of course produces the same results as 2.2 and 3.2:
@Query("{ 'name' : { $regex: ?0 } }")
List<User> findUsersByRegexpName(String regexp);
The usage is exactly the same:
List<User> users = userRepository.findUsersByRegexpName("^A");
List<User> users = userRepository.findUsersByRegexpName("c$");
4.3. $ LT and $GT
Now let's implement LT and GT queries:
@Query("{ 'age' : { $gt: ?0,$lt: ?1 } }")
List<User> findUsersByAgeBetween(int ageGT,int ageLT);
5. Conclusion
In this article, we discussed the common methods of query using spring data mongodb.
The sample of this article can be downloaded from spring data mongodb.
This article refers to a guide to queries in spring data mongodb