国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringBoot整合MongoDB

這篇具有很好參考價值的文章主要介紹了SpringBoot整合MongoDB。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。


提示:以下是本篇文章正文內(nèi)容,MongoDB 系列學(xué)習(xí)將會持續(xù)更新

SpringBoot整合MongoDB

一、環(huán)境準備

①添加 SpringData 依賴:

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

②配置 yml 文件,官方連接配置文檔

方式一:

spring:
  data:
    mongodb:
      uri: mongodb://root:123456@1.15.76.95:27017/library?authSource=admin

方式二:

spring:
  data:
    mongodb:
      username: root
      password: 123456
      host: 1.15.76.95
      port: 27017
      database: library
      authentication-database: admin

③直接注入 MongoTemplate 進行操作

@Resource
MongoTemplate mongoTemplate;

二、集合操作

@Test
public void testCollection(){
	boolean exists = mongoTemplate.collectionExists("borrow");
	if(exists) {
		// 刪除集合
		mongoTemplate.dropCollection("borrow");
	}else {
		// 創(chuàng)建集合
		mongoTemplate.createCollection("borrow");
	}
	Set<String> collectionNames = mongoTemplate.getCollectionNames();
    System.out.println(collectionNames.toString());  // [borrow, book, user]
}

回到目錄…

三、文檔操作

3.1 實體類

  • @Document
    • 修飾范圍:用在類上。
    • 作用:用來映射這個類的一個對象為 Mongo 中一條文檔數(shù)據(jù)。
    • 屬性:(value 、collection) 用來指定操作的集合名稱。
  • @MongoId
    • 修飾范圍:用在成員變量、方法上。
    • 作用:用來將成員變量的值映射為文檔的 _id 的值。
  • @Field
    • 修飾范圍:用在成員變量、方法上。
    • 作用:用來將成員變量及其值映射為文檔中一個 key:value 對。
    • 屬性:(name , value) 用來指定在文檔中 key 的名稱,默認為成員變量名。
  • @Transient
    • 修飾范圍:用在成員變量、方法上。
    • 作用:用來指定此成員變量不參與文檔的序列化。
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document("user")
public class User {
    @MongoId
    private Integer uid;
    @Field
    private String name;
    @Field
    private String password;
    @Field
    private Integer age;
}

回到目錄…

3.2 添加文檔

insert 方法返回值是新增的 Document 對象,里面包含了新增后 id 的值。如果集合不存在會自動創(chuàng)建集合。

@Test
public void test1() {
    // _id存在時更新數(shù)據(jù)
    mongoTemplate.save(new User(1, "aaa", "123456", 20));
    // _id存在時拋出異常
    mongoTemplate.insert(new User(2, "bbb", "113456", 21));

    List<User> list = Arrays.asList(
            new User(3, "ccc", "124266", 22),
            new User(4, "ddd", "136521", 23),
            new User(5, "eee", "147258", 24));
    // 批量插入
    mongoTemplate.insert(list, User.class);
}

通過 Spring Data MongoDB 還會給集合中多加一個 _class 的屬性,存儲新增時 Document 對應(yīng) Java 中類的全限定路徑。這么做為了查詢時能把 Document 轉(zhuǎn)換為 Java 類型。
SpringBoot整合MongoDB

回到目錄…

3.3 查詢文檔

  • Query 類作為查詢條件的容器,用于放置 Criteria 條件接口。
  • Criteria 是標準查詢的接口,可以引用靜態(tài)的 Criteria.where() 將字段和條件組合在一起進行查詢。
@Test
public void test1() {
	System.out.println("==========查詢所有文檔===========");
    List<User> list = mongoTemplate.findAll(User.class);
    list.forEach(System.out::println);

    System.out.println("==========根據(jù)_id查詢===========");
    User user = mongoTemplate.findById(3, User.class);
    System.out.println(user);

    System.out.println("==========findOne返回第一個文檔===========");
    User one = mongoTemplate.findOne(new Query(), User.class);
    System.out.println(one);
}
@Test
public void test2() {
	System.out.println("==========條件查詢===========");
	// 查詢name為"eee"的用戶
	Query query1 = new Query(Criteria.where("name").is("eee"));
	// 查詢 age<23 的用戶
	Query query2 = new Query(Criteria.where("age").lt(23));
	// 查詢 21<=age<24 的用戶
	Query query3 = new Query(Criteria.where("age").gte(21).lt(24));
	// 模糊查詢
	Query query4 = new Query(Criteria.where("password").regex("123"));

	System.out.println("==========多條件查詢===========");
	// 查詢 age<24 且 密碼包含"123" 的用戶
	Criteria criteria1 = new Criteria();
	criteria1.andOperator(Criteria.where("age").lt(24), Criteria.where("password").regex("123"));
	Query query5 = new Query(criteria1);
	// 查詢 age>23 或 密碼包含"456" 的用戶
	Criteria criteria2 = new Criteria();
	criteria2.orOperator(Criteria.where("age").gt(23), Criteria.where("password").regex("456"));
	Query query6 = new Query(criteria2);

	List<User> list = mongoTemplate.find(query6, User.class);
	list.forEach(System.out::println);
}
@Test
public void test3() {
	System.out.println("==========排序===========");
	Query query1 = new Query();
	query1.with(Sort.by(Sort.Order.desc("age")));

	System.out.println("==========分頁===========");
	Query query2 = new Query();
	query2.skip(0).limit(3);

	List<User> list = mongoTemplate.find(query2, User.class);
	list.forEach(System.out::println);
}

使用 JSON 字符串方式查詢:

@Test
public void testFindByJson() {
	// 等值查詢
	Query query1 = new BasicQuery("{name:'eee'}");
	// 多條件查詢
	Query query2 = new BasicQuery("{age:{$lt:24}, password:{$regex:'123'}}");
	Query query3 = new BasicQuery("{$or:[{age:{$gt:23}}, {password:{$regex:'456'}}]}");

	List<User> list = mongoTemplate.find(query3, User.class);
	list.forEach(System.out::println);
}

回到目錄…

3.4 修改文檔

在 Mongodb 中無論是使用客戶端 API 還是使用 Spring Data,更新返回結(jié)果一定是受行數(shù)影響。如果更新后的結(jié)果和更新前的結(jié)果是相同,返回 0。

  • updateFirst():只更新滿足條件的第一條記錄。
  • updateMulti():更新所有滿足條件的記錄。
  • upsert():沒有符合條件的記錄則插入數(shù)據(jù)。
@Test
public void test1() {
	Query query = new Query(Criteria.where("name").is("eee"));
	Update update = new Update();
	update.set("age", 25);
	// updateFirst() 只更新滿足條件的第一條記錄
	UpdateResult updateResult = mongoTemplate.updateFirst(query, update, User.class);
	System.out.println("返回修改的記錄數(shù): " + updateResult.getModifiedCount());
}
@Test
public void test2() {
	Query query = new Query(Criteria.where("age").gt(23));
	Update update = new Update();
	update.inc("age", 1);
	// updateMulti() 更新所有滿足條件的記錄
    UpdateResult updateResult = mongoTemplate.updateMulti(query, update, User.class);
	System.out.println("返回修改的記錄數(shù): " + updateResult.getModifiedCount());
}
@Test
public void test3() {
	// query查詢結(jié)果不存在
	Query query = new Query(Criteria.where("name").is("ggg"));
	Update update = new Update();
	update.set("age", 28);
	update.setOnInsert("_id", 7); //不存在時插入
	// upsert() 沒有符合條件的記錄則插入數(shù)據(jù)
	UpdateResult updateResult = mongoTemplate.upsert(query, update, User.class);
	System.out.println("返回修改的記錄數(shù): " + updateResult.getModifiedCount());
}

3.5 刪除文檔

@Test
public void testDelete() {
	//刪除所有文檔, 不如用dropCollection()
	//mongoTemplate.remove(new Query(),Employee.class);
        
	//條件刪除
	Query query = new Query(Criteria.where("name").is("fff"));
	mongoTemplate.remove(query, User.class);
}

回到目錄…

四、聚合操作

4.1 使用 Aggregation 實現(xiàn)

用 Aggregation 集合接收聚合操作,用 MongoTemplate 對象直接調(diào)用 aggregate,傳入聚合操作集合、表名、映射對象。

@Test
public void testAggregation() {
	// 1.先定義聚合操作
	MatchOperation match = Aggregation.match(Criteria.where("type").is("novel"));
	SortOperation sort = Aggregation.sort(Sort.Direction.ASC, "favCount");
	// 2.按順序組合每一個聚合步驟
	TypedAggregation<Book2> typedAggregation = Aggregation.newAggregation(Book2.class, match, sort);
	// 3.執(zhí)行聚合操作, 可以使用 Document、Map、自定義實體類 接收結(jié)果
	AggregationResults<Document> aggregate = mongoTemplate.aggregate(typedAggregation, Document.class);
	List<Document> results = aggregate.getMappedResults();
	results.forEach(System.out::println);
}

4.2 使用 Aggregates 實現(xiàn)

用 Aggregates 和 Bson 構(gòu)建聚合操作對象,用預(yù)先生成的 MongoCollection 對象調(diào)用 aggregate 執(zhí)行。

@Test
public void testAggregates(){
	// 1.先通過集合名拿到所有文檔
	MongoCollection<Document> collection = mongoTemplate.getCollection("book2");
	
	// 2.Aggregates提供各種聚合操作符,返回一個Bson對象
	Bson matchBson = Aggregates.match(new Document("type", "travel"));
//	Bson matchBson = Aggregates.match(Filters.eq("type", "travel"));//Filters來實現(xiàn)過濾
	Bson sortBson = Aggregates.sort(Sorts.ascending("favCount"));
//	Bson sortBson = Aggregates.sort(new Document("favCount", 1));
	
	// 3.構(gòu)建一個List<Bson>, 并把每一個聚合操作按順序加進去
	List<Bson> bsonList = new ArrayList<>();
	bsonList.add(matchBson);
	bsonList.add(sortBson);
	
	// 4.最后傳入aggregate方法中執(zhí)行,并且接收結(jié)果集
	AggregateIterable<Document> resultList = collection.aggregate(bsonList);
	resultList.forEach(System.out::println);
}

示例一:統(tǒng)計文檔中的書籍總量、收藏總數(shù)、平均收藏量

@Test
public void test1() {
    MongoCollection<Document> collection = mongoTemplate.getCollection("book2");

    Bson groupBson = Aggregates.group(null,
            Accumulators.sum("bookCount", 1),
            Accumulators.sum("favCount", "$favCount"),
            Accumulators.avg("favAvg", "$favCount"));

    List<Bson> bsonList = new ArrayList<>();
    bsonList.add(groupBson);

    AggregateIterable<Document> resultList = collection.aggregate(bsonList);
    resultList.forEach(System.out::println);
}

示例二:統(tǒng)計tag標簽的熱度排行 (根據(jù)favCount總量排行即為熱度)

@Test
public void test4() {
    MongoCollection<Document> collection = mongoTemplate.getCollection("book2");

    Bson unwindBson = Aggregates.unwind("$tag");
    Bson groupBson = Aggregates.group("$tag", Accumulators.sum("favCount", "$favCount"));
    Bson sortBson = Aggregates.sort(new Document("favCount", -1));

    List<Bson> bsonList = new ArrayList<>();
    bsonList.add(unwindBson);
    bsonList.add(groupBson);
    bsonList.add(sortBson);

    AggregateIterable<Document> resultList = collection.aggregate(bsonList);
    resultList.forEach(System.out::println);
}

回到目錄…

4.3 應(yīng)用案例

示例一:統(tǒng)計每個作者的每本book的收藏數(shù)

@Test
public void test1() {
    GroupOperation group = Aggregation
            .group("$author.name", "$title")
            .sum("$favCount").as("favCount");
    TypedAggregation<Book2> typedAggregation = Aggregation.newAggregation(Book2.class, group);
    AggregationResults<Document> aggregate = mongoTemplate.aggregate(typedAggregation, Document.class);
    List<Document> mappedResults = aggregate.getMappedResults();
    mappedResults.forEach(System.out::println);
}

示例二:每個作者的book的tag合集

@Test
public void test2() {
	UnwindOperation unwind = Aggregation.unwind("$tag");
    GroupOperation group = Aggregation
            .group("$author.name")
            .addToSet("$type").as("types");
    TypedAggregation<Book2> typedAggregation = Aggregation.newAggregation(Book2.class, unwind, group);
    AggregationResults<Document> aggregate = mongoTemplate.aggregate(typedAggregation, Document.class);
    List<Document> mappedResults = aggregate.getMappedResults();
    mappedResults.forEach(System.out::println);
}

示例三:聯(lián)表查詢用戶以及對應(yīng)的訂單信息

@Test
public void test1() {
    LookupOperation lookup = Aggregation.lookup("order", "_id", "customerId", "order");
    TypedAggregation<Customer> orderTypedAggregation = Aggregation.newAggregation(Customer.class, lookup);
    AggregationResults<Document> aggregate = mongoTemplate.aggregate(orderTypedAggregation, Document.class);
    List<Document> mappedResults = aggregate.getMappedResults();
    mappedResults.forEach(System.out::println);
}

SpringBoot整合MongoDB

示例四:聯(lián)表查詢訂單信息以及對應(yīng)的商品項

@Test
public void test2() {
    LookupOperation lookup = Aggregation.lookup("orderItem", "_id", "orderId", "orderItem");
    TypedAggregation<Order> orderItemTypedAggregation = Aggregation.newAggregation(Order.class, lookup);
    AggregationResults<Document> aggregate = mongoTemplate.aggregate(orderItemTypedAggregation, Document.class);
    List<Document> mappedResults = aggregate.getMappedResults();
    mappedResults.forEach(System.out::println);
}

SpringBoot整合MongoDB

回到目錄…


總結(jié):
提示:這里對文章進行總結(jié):
本文是對MongoDB的學(xué)習(xí),SpringBoot整合MongoDB的SpringData,配置文件中如何連接,實體類如何映射到文檔,如何通過API進行集合操作和文檔的增刪查改。之后的學(xué)習(xí)內(nèi)容將持續(xù)更新?。。?/font>文章來源地址http://www.zghlxwxcb.cn/news/detail-425410.html

到了這里,關(guān)于SpringBoot整合MongoDB的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • MongoDB - 整合 SpringBoot 操作全流程

    MongoDB - 整合 SpringBoot 操作全流程

    目錄 一、MongoDB 整合 SpringBoot 1.1、引入依賴 1.2、配置文件 1.3、集合操作 1.4、相關(guān)注解 1.5、文檔操作 1.5.1、查詢 1.5.2、更新 1.5.3、刪除 uri 格式為: mongodb://ip 地址:mongodb 端口號/集合名 Ps:以 demo 集合為例 a)創(chuàng)建集合 b)刪除集合 a)@Document 修飾范圍:在類上. 作用:映射當

    2024年01月17日
    瀏覽(16)
  • 【微服務(wù)】springboot整合mongodb使用詳解

    目錄 一、mongodb簡介 1.1 什么是mongodb 1.2 mongodb特點 二、mongodb中的核心術(shù)語 2.1 mogodb與數(shù)據(jù)庫對比

    2024年02月15日
    瀏覽(17)
  • springboot整合redis,MongoDB,Elasticsearch(ES)

    springboot整合redis,MongoDB,Elasticsearch(ES)

    目錄 ?springboot整合redis 連接Redis 字符串操作 哈希表操作 列表操作 集合操作 有序集合操作 lettcus與jedis的區(qū)別? springboot整合MongoDB 新增數(shù)據(jù) 查詢數(shù)據(jù) 更新數(shù)據(jù) 刪除數(shù)據(jù) ?springboot整合Elasticsearch(ES) 創(chuàng)建ElasticsearchRepository 創(chuàng)建實體類 增刪改查 搜索 Spring Boot整合Redis,需要使

    2024年02月05日
    瀏覽(22)
  • SpringBoot--中間件技術(shù)-3:整合mongodb,整合ElasticSearch,附案例含代碼(簡單易懂)

    實現(xiàn)步驟: pom文件導(dǎo)坐標 yaml配置文件配置mongodb: 隨便建一個pojo 測試: 裝配MongoTemplate模板類,調(diào)用方法 整合MongoDB總結(jié): 導(dǎo)坐標 寫配置文件 核心類MongoTemplate調(diào)用 前提準備:數(shù)據(jù)庫+ES 數(shù)據(jù)庫建表語句: 實現(xiàn)步驟: pom文件到坐標 yaml配置文件 創(chuàng)建實體類: 對應(yīng)數(shù)據(jù)庫表

    2024年02月04日
    瀏覽(19)
  • 13、MongoDB--通過 SpringBoot 整合 Spring Data MongoDB(【連接多個 MongoDB 服務(wù)器】、【高級定制 MongoDB 客戶端】的簡單介紹)

    放棄 Spring Boot 為 MongeDB 提供的自動配置,接下來同樣要干如下事情: 手動配置多組 ReactiveMongoDatabaseFactory 和 ReactiveMongoTemplate,要連幾個 MongoDB 服務(wù)器就配置幾組。 同步 API 則使用 MongoDatabaseFactory 和 MongoTemplate。 針對不同 MongoDB 服務(wù)器,分別開發(fā)相應(yīng)的 DAO 組件類,建議將它

    2024年03月19日
    瀏覽(25)
  • java springboot整合Mongodb 對數(shù)據(jù)庫集合進行增刪查改操作

    java springboot整合Mongodb 對數(shù)據(jù)庫集合進行增刪查改操作

    下面 我們就來做 springboot 整合Mongodb的工作 我們終端打開 Mongodb 安裝目錄下的bin目錄 然后執(zhí)行 啟動服務(wù) 然后 打開我們的 springboot 項目 在pom.xml 文件中 導(dǎo)入坐標 有了依賴之后 就還差配置 打開項目中的 application 配置文件 我這里用的 yml 格式 我們在上面 打個 mong 它就會彈出

    2024年01月18日
    瀏覽(23)
  • 【已解決】SpringBoot整合security賬號密碼正確卻提示錯誤

    【已解決】SpringBoot整合security賬號密碼正確卻提示錯誤

    SpringSecurity的密碼校驗并不是直接使用原文進行比較,而是使用加密算法將密碼進行加密(更準確地說應(yīng)該進行Hash處理,此過程是不可逆的,無法解密),最后將用戶提供的密碼以同樣的方式加密后與密文進行比較。對于我們來說,用戶提供的密碼屬于隱私信息,直接明文存

    2024年02月11日
    瀏覽(27)
  • SpringBoot整合es提示錯誤:ElasticsearchException[Invalid or missing build flavor [oss]]

    SpringBoot整合es提示錯誤:ElasticsearchException[Invalid or missing build flavor [oss]]

    SpringBoot整合es提示錯誤:ElasticsearchException[Invalid or missing build flavor [oss]] 問題屬于Springboot中引入的es版本與es服務(wù)版本不一致導(dǎo)致,當前項目引入es版本為 7.17.4 ,服務(wù)器版本為 7.8.1 ,版本修改統(tǒng)一即可;

    2024年02月13日
    瀏覽(12)
  • 開發(fā)微信小程序時,提示不在以下 request 合法域名列表中

    開發(fā)微信小程序時,提示不在以下 request 合法域名列表中

    如何解決這個問題呢? ** ** 在開發(fā)微信小程序的時候,注冊的時候都會有一個appid,這時候分兩種情況: (1)申請的測試環(huán)境,會分配一個測試用的appid (2)有真正的appid 解決方案: (1)打開微信開發(fā)者工具,找到右上角的\\\"詳情\\\"后點擊 (2) 找到本地設(shè)置,選中不校驗合法域名、

    2024年02月15日
    瀏覽(20)
  • 開發(fā)微信小程序時,提示不在以下 request 合法域名列表中怎么辦

    開發(fā)微信小程序時,提示不在以下 request 合法域名列表中怎么辦

    當開發(fā)微信小程序時,可能會出現(xiàn)以下提示:“request:fail url not in domain list(request:fail,當前請求域名不在后臺配置中,請確保請求域名在小程序后臺配置中)”。這是因為微信小程序的請求域名必須經(jīng)過后臺配置并且必須是合法的域名。 要解決此問題,您需要將您的請求

    2024年02月14日
    瀏覽(20)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包