To integrate Mongodb in Spring Boot, it is very easy to add the Starter package to Mongodb. The code is as follows:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Copy the code
Then configure Mongodb connection information:
Spring. The data. The mongo. Uri = mongo: / / 192.168.0.13 /test
Copy the code
For complete configuration information, see the following:
spring.data.mongodb.authentication-database= # Authentication database name.
spring.data.mongodb.database= # Database name.
spring.data.mongodb.field-naming-strategy= # Fully qualified name of the FieldNamingStrategy to use.
spring.data.mongodb.grid-fs-database= # GridFS database name.
spring.data.mongodb.host= # Mongo server host. Cannot be set with URI.
spring.data.mongodb.password= # Login password of the mongo server. Cannot be set with URI.
spring.data.mongodb.port= # Mongo server port. Cannot be set with URI.
spring.data.mongodb.repositories.type=auto # Type of Mongo repositories to enable.
spring.data.mongodb.uri=mongodb://localhost/test # Mongo database URI. Cannot be set with host, port and credentials.
spring.data.mongodb.username= # Login user of the mongo server. Cannot be set with URI.
Copy the code
Once configured, you can directly inject the MongoTemplate operation data
Add data
First create an entity class, we use the article as the entity class, define the following fields:
import java.util.Date; import java.util.List; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; /** * @author yinjihuan ** / @document (collection ="article_info")
public class Article {
@Id
private String id;
@Field("title")
private String title;
@Field("url")
private String url;
@Field("author")
private String author;
@Field("tags")
private List<String> tags;
@Field("visit_count")
private Long visitCount;
@Field("add_time") private Date addTime; / / omit the getsetMethods}Copy the code
1. The Document annotation indicates that this is a Document, which is equivalent to the table in mysql. The collection value represents the name of the collection in mongodb. The spring-data. Mongodb uses this annotation to allow users to define Field names that are inconsistent with the entity class. It also has the advantage of being able to use short names. For example, username can be set to unane or UN, which can save storage space. Mongodb is stored in the form of key value, and each key will be stored repeatedly. In fact, the key occupies a large amount of storage space.
Now you can manipulate the database, and then, last time, write code in the test class
@Autowired private MongoTemplate mongoTemplate; @author yinjihuan */ public static voidinitArticle() {// loop addfor (int i = 0; i < 10; i++) {
Article article = new Article();
article.setTitle(MongoTemplate Basic Use);
article.setAuthor("yinjihuan");
article.setUrl("http://cxytiandi.com/blog/detail/" + i);
article.setTags(Arrays.asList("java"."mongodb"."spring"));
article.setVisitCount(0L);
article.setAddTime(new Date());
mongoTemplate.save(article);
}
//批量添加
List<Article> articles = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
Article article = new Article();
article.setTitle(MongoTemplate Basic Use);
article.setAuthor("yinjihuan");
article.setUrl("http://cxytiandi.com/blog/detail/" + i);
article.setTags(Arrays.asList("java"."mongodb"."spring"));
article.setVisitCount(0L);
article.setAddTime(new Date());
articles.add(article);
}
mongoTemplate.insert(articles, Article.class);
}
Copy the code
Batch add performance is better in the case of large data volume.
Delete operation
Query Query = Query. Query (Criteria. Where ("author").is("yinjihuan"));
mongoTemplate.remove(query, Article.class);
Copy the code
// Article_info query = query.query (Criteria. Where ()"author").is("yinjihuan"));
mongoTemplate.remove(query, "article_info");
Copy the code
/ / delete collection, but the entity class, can also pass the name mongoTemplate. DropCollection (Article. Class); mongoTemplate.dropCollection("article_info");
Copy the code
Mongotemplate.getdb ().dropdatabase ();Copy the code
The following two scenarios are suitable for situations where you need to know what data is being deleted, such as recording deleted records
Query = query.query (Criteria. Where (Criteria."author").is("yinjihuan"));
Article article = mongoTemplate.findAndRemove(query, Article.class);
Copy the code
Query = query.query (Criteria. Where (Criteria."author").is("yinjihuan"));
List<Article> articles = mongoTemplate.findAllAndRemove(query, Article.class);
Copy the code
Modify the operating
First initialize the data to be modified
{
"_id": ObjectId("57c43caed4c63d7e39b5dc48"),
"title": MongoTemplate Basic Use."url": "http://cxytiandi.com/blog/detail/0"."author": "yinjihuan"."tags": [
"java"."mongodb"."spring"]."visit_count": 0."add_time": ISODate("The 2016-08-29 T13:46:21. 881 z")} {"_id": ObjectId("57c43caed4c63d7e39b5dc49"),
"title": MongoTemplate Basic Use."url": "http://cxytiandi.com/blog/detail/1"."author": "yinjihuan"."tags": [
"java"."mongodb"."spring"]."visit_count": 0."add_time": ISODate("The 2016-08-29 T13: in 201 z")}Copy the code
// Modify title and visitCount Query Query = Query. Query (Criteria."author").is("yinjihuan"));
Update update = Update.update("title"."MongoTemplate").set("visitCount", 10);
mongoTemplate.updateFirst(query, update, Article.class);
Copy the code
We can see that the title and visit_count of the first data have been changed
{
"_id": ObjectId("57c43caed4c63d7e39b5dc48"),
"title": "MongoTemplate"."url": "http://cxytiandi.com/blog/detail/0"."author": "yinjihuan"."tags": [
"java"."mongodb"."spring"]."visit_count": 10,
"add_time": ISODate("The 2016-08-29 T13:46:21. 881 z")} {"_id": ObjectId("57c43caed4c63d7e39b5dc49"),
"title": MongoTemplate Basic Use."url": "http://cxytiandi.com/blog/detail/1"."author": "yinjihuan"."tags": [
"java"."mongodb"."spring"]."visit_count": 0."add_time": ISODate("The 2016-08-29 T13: in 201 z")}Copy the code
Query = query. Query (Criteria. Where ("author").is("yinjihuan"));
update = Update.update("title"."MongoTemplate").set("visitCount", 10);
mongoTemplate.updateMulti(query, update, Article.class);
Copy the code
The result is as follows. We can see that title and visit_count of all data have been changed
{
"_id": ObjectId("57c43caed4c63d7e39b5dc48"),
"title": "MongoTemplate"."url": "http://cxytiandi.com/blog/detail/0"."author": "yinjihuan"."tags": [
"java"."mongodb"."spring"]."visit_count": 10,
"add_time": ISODate("The 2016-08-29 T13:46:21. 881 z")} {"_id": ObjectId("57c43caed4c63d7e39b5dc49"),
"title": "MongoTemplate"."url": "http://cxytiandi.com/blog/detail/1"."author": "yinjihuan"."tags": [
"java"."mongodb"."spring"]."visit_count": 10,
"add_time": ISODate("The 2016-08-29 T13: in 201 z")}Copy the code
If there is no data whose author is Jason, a new data is created based on this condition. If there is no matching document, a new document is created based on this condition and the updated document. If a matching document is found, the normal update is performed. query = Query.query(Criteria.where("author").is("jason"));
update = Update.update("title"."MongoTemplate").set("visitCount", 10);
mongoTemplate.upsert(query, update, Article.class);
Copy the code
The result is as follows, and we will see that a new data is added
{
"_id": ObjectId("57c43caed4c63d7e39b5dc48"),
"title": "MongoTemplate"."url": "http://cxytiandi.com/blog/detail/0"."author": "yinjihuan"."tags": [
"java"."mongodb"."spring"]."visit_count": 10,
"add_time": ISODate("The 2016-08-29 T13:46:21. 881 z")} {"_id": ObjectId("57c43caed4c63d7e39b5dc49"),
"title": "MongoTemplate"."url": "http://cxytiandi.com/blog/detail/1"."author": "yinjihuan"."tags": [
"java"."mongodb"."spring"]."visit_count": 10,
"add_time": ISODate("The 2016-08-29 T13: in 201 z")} {"_id": ObjectId("57c6e1601e4735b2c306cdb7"),
"author": "jason"."title": "MongoTemplate"."visit_count"10} :Copy the code
// The update condition is unchanged, the update field is changed to one that does not exist in our collectionsetQuery = query.query (Criteria. Where (Criteria."author").is("jason"));
update = Update.update("title"."MongoTemplate").set("money", 100);
mongoTemplate.updateMulti(query, update, Article.class);
Copy the code
The result is as follows. We can see that a new key has been added
{
"_id": ObjectId("57c6e1601e4735b2c306cdb7"),
"author": "jason"."title": "MongoTemplate"."visit_count": 10,
"money":100
}
Copy the code
Query = query. Query (Criteria. Where (Criteria."author").is("jason"));
update = Update.update("title"."MongoTemplate").inc("money", 100);
mongoTemplate.updateMulti(query, update, Article.class);
Copy the code
After modification, the result is as follows. We will find that Money becomes 200
{
"_id": ObjectId("57c6e1601e4735b2c306cdb7"),
"author": "jason"."title": "MongoTemplate"."visit_count": 10,
"money":200
}
Copy the code
Query = query.query (Criteria. Where (Criteria."author").is("jason"));
update = Update.update("title"."MongoTemplate").rename("visitCount"."vc");
mongoTemplate.updateMulti(query, update, Article.class);
Copy the code
{
"_id": ObjectId("57c6e1601e4735b2c306cdb7"),
"author": "jason"."title": "MongoTemplate"."vc": 10,
"money":200
}
Copy the code
/ / updateunsetQuery = query.query (Criteria. Where (Criteria."author").is("jason"));
update = Update.update("title"."MongoTemplate").unset("vc");
mongoTemplate.updateMulti(query, update, Article.class);
Copy the code
The result is as follows, we will find that the VC key has been deleted
{
"_id": ObjectId("57c6e1601e4735b2c306cdb7"),
"author": "jason"."title": "MongoTemplate"."money":200
}
Copy the code
Java query = query.query (Criteria. Where ("author").is("yinjihuan"));
update = Update.update("title"."MongoTemplate").pull("tags"."java");
mongoTemplate.updateMulti(query, update, Article.class);
Copy the code
The result is as follows, we can see that the Java in the tags has been removed
{
"_id": ObjectId("57c43caed4c63d7e39b5dc48"),
"title": "MongoTemplate"."url": "http://cxytiandi.com/blog/detail/0"."author": "yinjihuan"."tags": [
"mongodb"."spring"]."visit_count": 10,
"add_time": ISODate("The 2016-08-29 T13:46:21. 881 z")} {"_id": ObjectId("57c43caed4c63d7e39b5dc49"),
"title": "MongoTemplate"."url": "http://cxytiandi.com/blog/detail/1"."author": "yinjihuan"."tags": [
"mongodb"."spring"]."visit_count": 10,
"add_time": ISODate("The 2016-08-29 T13: in 201 z")}Copy the code
Query operation
Query, whether relational database or noSQL like mongodb, is used more, most of the operations are read operations. There are many query methods of mongodb. The following lists some common ones, for example: 1.= Query 2. Fuzzy query 3. Greater than or less than query 4. In query 5. Or query 6. 7. Learn by yourself…
Query all eligible data according to author, return List
Query query = Query.query(Criteria.where("author").is("yinjihuan"));
List<Article> articles = mongoTemplate.find(query, Article.class);
Copy the code
Query only the first data that matches the condition, returning the Article object
query = Query.query(Criteria.where("author").is("yinjihuan"));
Article article = mongoTemplate.findOne(query, Article.class);
Copy the code
Query all data in the collection without conditions
articles = mongoTemplate.findAll(Article.class);
Copy the code
Query the number of conditions
query = Query.query(Criteria.where("author").is("yinjihuan"));
long count = mongoTemplate.count(query, Article.class);
Copy the code
Query by primary key ID
article = mongoTemplate.findById(new ObjectId("57c6e1601e4735b2c306cdb7"), Article.class);
Copy the code
In the query
List<String> authors = Arrays.asList("yinjihuan"."jason");
query = Query.query(Criteria.where("author").in(authors));
articles = mongoTemplate.find(query, Article.class);
Copy the code
Ne (! =) query
query = Query.query(Criteria.where("author").ne("yinjihuan"));
articles = mongoTemplate.find(query, Article.class);
Copy the code
Lt (<) queries articles with less than 10 views
query = Query.query(Criteria.where("visitCount").lt(10));
articles = mongoTemplate.find(query, Article.class);
Copy the code
Range query, greater than 5 and less than 10
query = Query.query(Criteria.where("visitCount").gt(5).lt(10));
articles = mongoTemplate.find(query, Article.class);
Copy the code
Fuzzy query, author contains data of A
query = Query.query(Criteria.where("author").regex("a"));
articles = mongoTemplate.find(query, Article.class);
Copy the code
Array query, query the number of 3 in tags
query = Query.query(Criteria.where("tags").size(3));
articles = mongoTemplate.find(query, Article.class);
Copy the code
Where author= Jason or visitCount=0
query = Query.query(Criteria.where("").orOperator(
Criteria.where("author").is("jason"),
Criteria.where("visitCount").is(0)));
articles = mongoTemplate.find(query, Article.class);
Copy the code
For more technology sharing, please pay attention to wechat public number: Ape World