Spring Boot中快速操作Mongodb數據庫指南

前言

在Spring Boot中集成Mongodb非常簡單,隻需要加入Mongodb的Starter包即可,代碼如下:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

然後配置Mongodb的連接信息:

spring.data.mongodb.uri=mongodb://192.168.0.13/test

完整配置信息請參考下面:

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.

配置好瞭之後就直接可以註入MongoTemplate操作數據瞭

添加數據

首先創建一個實體類,我們這邊用文章來做實體類,定義如下字段:

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;
    
    //省略get set方法
}

實體類中的註解解釋如下:

1.Document註解標識這是一個文檔,等同mysql中的表,collection值表示mongodb中集合的名稱,不寫默認為實體類名article。

2.Id註解為主鍵標識

3.Field註解為字段標識,指定值為字段名稱,這邊有個小技巧,之所有spring-data.mongodb中有這樣的註解,是為瞭能夠讓用戶自定義字段名稱,可以和實體類不一致,還有個好處就是可以用縮寫,比如username我們可以配置成unane或者un,這樣的好處是節省瞭存儲空間,mongodb的存儲方式是key value形式的,每個key就會重復存儲,key其實就占瞭很大一份存儲空間。
接下來可以操作數據庫瞭,接著上次,在測試類裡寫代碼

@Autowired
private MongoTemplate mongoTemplate;

/**
 * 初始化文章信息
 * @author yinjihuan
 */
public static void initArticle() {
    //循環添加
    for (int i = 0; i < 10; i++) {
        Article article = new Article();
        article.setTitle("MongoTemplate的基本使用");
	    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的基本使用");
	    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);
  
}

在數據量大的情況下批量添加性能會更好哦。

刪除操作

//刪除author為yinjihuan的數據
Query query = Query.query(Criteria.where("author").is("yinjihuan"));
mongoTemplate.remove(query, Article.class);
//如果實體類中沒配集合名詞,可在刪除的時候單獨指定article_info
query = Query.query(Criteria.where("author").is("yinjihuan"));
mongoTemplate.remove(query, "article_info");
//刪除集合,可傳實體類,也可以傳名稱
mongoTemplate.dropCollection(Article.class);
mongoTemplate.dropCollection("article_info");
//刪除數據庫
mongoTemplate.getDb().dropDatabase();

下面這2種適合要知道刪除的數據有哪些的場景,比如記錄刪除的記錄

//查詢出符合條件的第一個結果,並將符合條件的數據刪除,隻會刪除第一條
query = Query.query(Criteria.where("author").is("yinjihuan"));
Article article = mongoTemplate.findAndRemove(query, Article.class);
//查詢出符合條件的所有結果,並將符合條件的所有數據刪除
query = Query.query(Criteria.where("author").is("yinjihuan"));
List<Article> articles = mongoTemplate.findAllAndRemove(query, Article.class);

修改操作

首先初始化需要修改的數據

{
    "_id": ObjectId("57c43caed4c63d7e39b5dc48"),
    "title": "MongoTemplate的基本使用",
    "url": "http://cxytiandi.com/blog/detail/0",
    "author": "yinjihuan",
    "tags": [
        "java",
        "mongodb",
        "spring"
    ],
    "visit_count": 0,
    "add_time": ISODate("2016-08-29T13:46:21.881Z")
}
{
    "_id": ObjectId("57c43caed4c63d7e39b5dc49"),
    "title": "MongoTemplate的基本使用",
    "url": "http://cxytiandi.com/blog/detail/1",
    "author": "yinjihuan",
    "tags": [
        "java",
        "mongodb",
        "spring"
    ],
    "visit_count": 0,
    "add_time": ISODate("2016-08-29T13:46:22.201Z")
}
//修改第一條author為yinjihuan的數據中的title和visitCount
Query query = Query.query(Criteria.where("author").is("yinjihuan"));
Update update = Update.update("title", "MongoTemplate").set("visitCount", 10);
mongoTemplate.updateFirst(query, update, Article.class);

修改後結果如下,我們會發現第一條數據的title還有visit_count被修改瞭

{
    "_id": ObjectId("57c43caed4c63d7e39b5dc48"),
    "title": "MongoTemplate",
    "url": "http://cxytiandi.com/blog/detail/0",
    "author": "yinjihuan",
    "tags": [
        "java",
        "mongodb",
        "spring"
    ],
    "visit_count": 10,
    "add_time": ISODate("2016-08-29T13:46:21.881Z")
}
{
    "_id": ObjectId("57c43caed4c63d7e39b5dc49"),
    "title": "MongoTemplate的基本使用",
    "url": "http://cxytiandi.com/blog/detail/1",
    "author": "yinjihuan",
    "tags": [
        "java",
        "mongodb",
        "spring"
    ],
    "visit_count": 0,
    "add_time": ISODate("2016-08-29T13:46:22.201Z")
}
//修改全部符合條件的
query = Query.query(Criteria.where("author").is("yinjihuan"));
update = Update.update("title", "MongoTemplate").set("visitCount", 10);
mongoTemplate.updateMulti(query, update, Article.class);

修改後結果如下,我們會發現所有數據的title還有visit_count被修改瞭

{
    "_id": ObjectId("57c43caed4c63d7e39b5dc48"),
    "title": "MongoTemplate",
    "url": "http://cxytiandi.com/blog/detail/0",
    "author": "yinjihuan",
    "tags": [
        "java",
        "mongodb",
        "spring"
    ],
    "visit_count": 10,
    "add_time": ISODate("2016-08-29T13:46:21.881Z")
}
{
    "_id": ObjectId("57c43caed4c63d7e39b5dc49"),
    "title": "MongoTemplate",
    "url": "http://cxytiandi.com/blog/detail/1",
    "author": "yinjihuan",
    "tags": [
        "java",
        "mongodb",
        "spring"
    ],
    "visit_count": 10,
    "add_time": ISODate("2016-08-29T13:46:22.201Z")
}
//特殊更新,更新author為jason的數據,如果沒有author為jason的數據則以此條件創建一條新的數據
//當沒有符合條件的文檔,就以這個條件和更新文檔為基礎創建一個新的文檔,如果找到匹配的文檔就正常的更新。
query = Query.query(Criteria.where("author").is("jason"));
update = Update.update("title", "MongoTemplate").set("visitCount", 10);
mongoTemplate.upsert(query, update, Article.class);

修改後結果如下,我們會發現新增瞭一條數據

{
    "_id": ObjectId("57c43caed4c63d7e39b5dc48"),
    "title": "MongoTemplate",
    "url": "http://cxytiandi.com/blog/detail/0",
    "author": "yinjihuan",
    "tags": [
        "java",
        "mongodb",
        "spring"
    ],
    "visit_count": 10,
    "add_time": ISODate("2016-08-29T13:46:21.881Z")
}
{
    "_id": ObjectId("57c43caed4c63d7e39b5dc49"),
    "title": "MongoTemplate",
    "url": "http://cxytiandi.com/blog/detail/1",
    "author": "yinjihuan",
    "tags": [
        "java",
        "mongodb",
        "spring"
    ],
    "visit_count": 10,
    "add_time": ISODate("2016-08-29T13:46:22.201Z")
}
{
    "_id": ObjectId("57c6e1601e4735b2c306cdb7"),
    "author": "jason",
    "title": "MongoTemplate",
    "visit_count": 10
}
//更新條件不變,更新字段改成瞭一個我們集合中不存在的,用set方法如果更新的key不存在則創建一個新的key
query = Query.query(Criteria.where("author").is("jason"));
update = Update.update("title", "MongoTemplate").set("money", 100);
mongoTemplate.updateMulti(query, update, Article.class);

修改後結果如下,我們會發現新加瞭一個key

{
    "_id": ObjectId("57c6e1601e4735b2c306cdb7"),
    "author": "jason",
    "title": "MongoTemplate",
    "visit_count": 10,
    "money":100
}
//update的inc方法用於做累加操作,將money在之前的基礎上加上100
query = Query.query(Criteria.where("author").is("jason"));
update = Update.update("title", "MongoTemplate").inc("money", 100);
mongoTemplate.updateMulti(query, update, Article.class);

修改後結果如下,我們會發現money變成200

{
    "_id": ObjectId("57c6e1601e4735b2c306cdb7"),
    "author": "jason",
    "title": "MongoTemplate",
    "visit_count": 10,
    "money":200
}
//update的rename方法用於修改key的名稱
query = Query.query(Criteria.where("author").is("jason"));
update = Update.update("title", "MongoTemplate").rename("visitCount", "vc");
mongoTemplate.updateMulti(query, update, Article.class);
{
    "_id": ObjectId("57c6e1601e4735b2c306cdb7"),
    "author": "jason",
    "title": "MongoTemplate",
    "vc": 10,
    "money":200
}
//update的unset方法用於刪除key
query = Query.query(Criteria.where("author").is("jason"));
update = Update.update("title", "MongoTemplate").unset("vc");
mongoTemplate.updateMulti(query, update, Article.class);

修改後結果如下,我們會發現vc這個key被刪除瞭

{
    "_id": ObjectId("57c6e1601e4735b2c306cdb7"),
    "author": "jason",
    "title": "MongoTemplate",
    "money":200
}
//update的pull方法用於刪除tags數組中的java
query = Query.query(Criteria.where("author").is("yinjihuan"));
update = Update.update("title", "MongoTemplate").pull("tags", "java");
mongoTemplate.updateMulti(query, update, Article.class);

修改後結果如下,我們會發現tags裡的java被刪除瞭

{
    "_id": ObjectId("57c43caed4c63d7e39b5dc48"),
    "title": "MongoTemplate",
    "url": "http://cxytiandi.com/blog/detail/0",
    "author": "yinjihuan",
    "tags": [
        "mongodb",
        "spring"
    ],
    "visit_count": 10,
    "add_time": ISODate("2016-08-29T13:46:21.881Z")
}
{
    "_id": ObjectId("57c43caed4c63d7e39b5dc49"),
    "title": "MongoTemplate",
    "url": "http://cxytiandi.com/blog/detail/1",
    "author": "yinjihuan",
    "tags": [
        "mongodb",
        "spring"
    ],
    "visit_count": 10,
    "add_time": ISODate("2016-08-29T13:46:22.201Z")
}

查詢操作

查詢,無論是關系型數據庫還是mongodb這種nosql,都是使用比較多的,大部分操作都是讀的操作。

mongodb的查詢方式很多種,下面隻列瞭一些常用的,比如:

1.=查詢

2.模糊查詢

3.大於小於范圍查詢

4.in查詢

5.or查詢

6.查詢一條,查詢全部

7.自己慢慢學習…

根據作者查詢所有符合條件的數據,返回List

Query query = Query.query(Criteria.where("author").is("yinjihuan"));
List<Article> articles = mongoTemplate.find(query, Article.class);

隻查詢符合條件的第一條數據,返回Article對象

query = Query.query(Criteria.where("author").is("yinjihuan"));
Article article = mongoTemplate.findOne(query, Article.class);

查詢集合中所有數據,不加條件

articles = mongoTemplate.findAll(Article.class);

查詢符合條件的數量

query = Query.query(Criteria.where("author").is("yinjihuan"));
long count = mongoTemplate.count(query, Article.class);

根據主鍵ID查詢

article = mongoTemplate.findById(new ObjectId("57c6e1601e4735b2c306cdb7"), Article.class);

in查詢

List<String> authors = Arrays.asList("yinjihuan", "jason");
query = Query.query(Criteria.where("author").in(authors));
articles = mongoTemplate.find(query, Article.class);

ne(!=)查詢

query = Query.query(Criteria.where("author").ne("yinjihuan"));
articles = mongoTemplate.find(query, Article.class);

lt(<)查詢訪問量小於10的文章

query = Query.query(Criteria.where("visitCount").lt(10));
articles = mongoTemplate.find(query, Article.class);

范圍查詢,大於5小於10

query = Query.query(Criteria.where("visitCount").gt(5).lt(10));
articles = mongoTemplate.find(query, Article.class);

模糊查詢,author中包含a的數據

query = Query.query(Criteria.where("author").regex("a"));
articles = mongoTemplate.find(query, Article.class);

數組查詢,查詢tags裡數量為3的數據

query = Query.query(Criteria.where("tags").size(3));
articles = mongoTemplate.find(query, Article.class);

or查詢,查詢author=jason的或者visitCount=0的數據

query = Query.query(Criteria.where("").orOperator(
    Criteria.where("author").is("jason"),
    Criteria.where("visitCount").is(0)));
articles = mongoTemplate.find(query, Article.class);

總結

到此這篇關於Spring Boot中如何快速操作Mongodb的文章就介紹到這瞭,更多相關SpringBoot操作Mongodb內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: