《Netkiller Spring Cloud 手札》Spring boot 2.0 mongoTemplate 操作范例

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

本文節選自 《Netkiller Spring Cloud 手札》

?

Netkiller Spring Cloud 手札

Spring Cloud Cookbook

Mr.?Neo?Chan,?陳景峯(BG7NYT)



中國廣東省深圳市望海路半島城邦三期
518067
+86?13113668890

<netkiller@msn.com>

$Id: book.xml 606 2013-05-29 09:52:58Z netkiller $

版權 ? 2015-2018 Neo Chan

?

版權聲明

轉載請與作者聯系,轉載時請務必標明文章原始出處和作者信息及本聲明。

31213359_sbuN.png
http://www.netkiller.cn
http://netkiller.github.io
http://netkiller.sourceforge.net
31213359_RL5o.jpg
微信訂閱號 netkiller-ebook (微信掃描二維碼)
QQ:13721218 請注明“讀者”
QQ群:128659835 請注明“讀者”

?

2017-11

我的系列文檔

編程語言

Netkiller Architect 手札Netkiller Developer 手札Netkiller Java 手札Netkiller Spring 手札Netkiller PHP 手札Netkiller Python 手札
Netkiller Testing 手札Netkiller Cryptography 手札Netkiller Perl 手札Netkiller Docbook 手札Netkiller Project 手札Netkiller Database 手札

5.2.4.?mongoTemplate

導入與模板相關的包

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

注入 MongoTemplate 對象

@Autowiredprivate MongoTemplate mongoTemplate;

5.2.4.1.?Save 保存

User user = new User();
user.setName("Netkiller"); 
mongoTemplate.save(user, "user");

更新數據

user = mongoTemplate.findOne(Query.query(Criteria.where("name").is("Jam")), User.class);
user.setName("Neo");
mongoTemplate.save(user, "user");

5.2.4.2.?Insert

User user = new User();
user.setName("Neo");
mongoTemplate.insert(user, "user");
BSONObject personBsonObj = BasicDBObjectBuilder.start().add("name","Neo Chen").add("age",27).add("address",null).get();mongoTemplate.insert(personBsonObj,"personCollection");

document in the db:

db.personCollection.findOne().pretty();
{"age":21,"name":"John Doe";"address":null}*

5.2.4.3.?更新第一條

Query query = new Query();
query.addCriteria(Criteria.where("name").is("Neo"));
Update update = new Update();
update.set("name", "Netkiller");
mongoTemplate.updateFirst(query, update, User.class);

5.2.4.4.?更新所有數據

Query query = new Query();
query.addCriteria(Criteria.where("name").is("Neo"));
Update update = new Update();
update.set("name", "Jerry");
mongoTemplate.updateMulti(query, update, User.class);

5.2.4.5.?查找并保存

Query query = new Query();
query.addCriteria(Criteria.where("name").is("Luck"));
Update update = new Update();
update.set("name", "Lisa");
User user = mongoTemplate.findAndModify(query, update, User.class);

5.2.4.6.?upsert

Query query = new Query();
query.addCriteria(Criteria.where("name").is("Green"));
Update update = new Update();
update.set("name", "Tom");
mongoTemplate.upsert(query, update, User.class);

5.2.4.7.?刪除

User user = new User();
user.setId("5bbf091efd9557069c4a25c5")			
mongoTemplate.remove(user, "user");

5.2.4.8.?查找一條數據

public Person findOneByName(String name) {Query query = new Query();query.addCriteria(Criteria.where("name").is(name));return mongoTemplate.findOne(query, Person.class);
}

5.2.4.9.?查找所有數據

public List<Person> findByName(String name) {Query query = new Query();query.addCriteria(Criteria.where("name").is(name));return mongoTemplate.find(query, Person.class);
}

5.2.4.10.?Query

5.2.4.10.1.?翻頁

public List<Person> getAllPersonPaginated(int pageNumber, int pageSize) {Query query = new Query();query.skip(pageNumber * pageSize);query.limit(pageSize);return mongoTemplate.find(query, Person.class);
}

5.2.4.10.2.?between

實現一個區間條件 new Criteria("createdDate").gte(beginDate).lte(endDate)

public boolean AccountDeposit(Date beginDate, Date endDate) {MatchOperation matchOperation = match(new Criteria("createdDate").gte(beginDate).lte(endDate));GroupOperation groupOperation = group("loginname").sum("amount").as("amount");SortOperation sortOperation = sort(new Sort(Direction.ASC, "loginname"));Aggregation aggregation = newAggregation(matchOperation, groupOperation, sortOperation);AggregationResults<AccountSettlementDetails> results = mongoTemplate.aggregate(aggregation, AccountSettlementDetails.class, AccountSettlementDetails.class);if (results.getMappedResults() != null) {log.info(results.getRawResults().get("result").toString());for (AccountSettlementDetails settlementDetails : results.getMappedResults()) {log.info("{}", settlementDetails.toString());}}return true;}

5.2.4.11.?Criteria

5.2.4.11.1.?is

Query query = new Query();
query.addCriteria(Criteria.where("name").is("Neo"));
List<User> users = mongoTemplate.find(query, User.class);

5.2.4.11.2.?Regex 正則表達式搜索

查詢以N開頭的名字

Query query = new Query();
query.addCriteria(Criteria.where("name").regex("^N"));
List<User> users = mongoTemplate.find(query,User.class);

查詢以o結尾的名字

Query query = new Query();
query.addCriteria(Criteria.where("name").regex("o$"));
List<User> users = mongoTemplate.find(query, User.class);

5.2.4.11.3.?lt 和 gt

查詢年齡小于 < 30 并 > 20 的用戶

Query query = new Query();
query.addCriteria(Criteria.where("age").lt(30).gt(20));
List<User> users = mongoTemplate.find(query,User.class);

查找日期范圍

Date start = DateUtil.convertStringToDateTime("2014-02-10 20:38:44");
Date end = DateUtil.convertStringToDateTime("2014-02-10 20:38:50");Query query = new Query();
Criteria criteria = Criteria.where("delflag").is(false);
criteria.and("modifyDate").gte(start).lte(end);
query.addCriteria(criteria);
query.limit(10);

5.2.4.11.4.?

<programlisting><![CDATA[
Query query = new Query();
query.addCriteria(new Criteria().andOperator(Criteria.where("field1").exists(true),Criteria.where("field1").ne(false))
);List<Foo> result = mongoTemplate.find(query, Foo.class);
System.out.println("query - " + query.toString());for (Foo foo : result) {System.out.println("result - " + foo);
}

5.2.4.11.5.?包含

public List<Person> findByFavoriteBooks(String favoriteBook) {Query query = new Query();query.addCriteria(Criteria.where("favoriteBooks").in(favoriteBook));return mongoTemplate.find(query, Person.class);
}

5.2.4.12.?Update

5.2.4.12.1.?set

Update update = new Update();
update.set("name", "Netkiller");

5.2.4.12.2.?追加數據

Query query = Query.query(Criteria.where("id").is("5bbf091efd9557069c4a25c5"));Update update = new Update().push("author", new Author("neo", "chen"));mongoTemplate.updateFirst(query, update, Article.class);

5.2.4.12.3.?更新數據

Query query = Query.query(Criteria.where("classId").is("1").and("Students.studentId").is("1"));Update update = Update.update("Students.$.name", "lisa");mongoTemplate.upsert(query, update, "class");

5.2.4.12.4.?刪除數據

Query query = Query.query(Criteria.where("classId").is("1").and("Students.studentId").is("3"));Update update = new Update();update.unset("Students.$");mongoTemplate.updateFirst(query, update, "class");

5.2.4.12.5.?inc

public void updateMultiplePersonAge() {Query query = new Query();Update update = new Update().inc("age", 1);mongoTemplate.findAndModify(query, update, Person.class);;
}

5.2.4.12.6.?update.addToSet

Query query = Query.query(Criteria.where("classId").is("1"));
Student student = new Student("1", "lisa", 3, "girl");
Update update = new Update();
update.addToSet("Students", student);
mongoTemplate.upsert(query, update, "class");

5.2.4.13.?Sort

按照年齡排序

Query query = new Query();
query.with(new Sort(Sort.Direction.ASC, "age"));
List<User> users = mongoTemplate.find(query,User.class);

5.2.4.14.?Query + PageRequest

final Pageable pageableRequest = new PageRequest(0, 2);
Query query = new Query();
query.with(pageableRequest);

5.2.4.15.?newAggregation

MultilevelDirectSellingAccountRewardsSettlementDetails multilevelDirectSellingAccountRewardsSettlementDetails = new MultilevelDirectSellingAccountRewardsSettlementDetails();multilevelDirectSellingAccountRewardsSettlementDetails.setLoginname("111");multilevelDirectSellingAccountRewardsSettlementDetails.setPhone("111");multilevelDirectSellingAccountRewardsSettlementDetails.setRecommenderLoginname("111");multilevelDirectSellingAccountRewardsSettlementDetails.setRecommenderPhone("111");multilevelDirectSellingAccountRewardsSettlementDetails.setRecommenderName("Neo");multilevelDirectSellingAccountRewardsSettlementDetails.setRecommenderType("客戶");multilevelDirectSellingAccountRewardsSettlementDetails.setAmount(5.02);multilevelDirectSellingAccountRewardsSettlementDetails.setCreatedDate(new Date());multilevelDirectSellingAccountRewardsSettlementDetailsRepository.save(multilevelDirectSellingAccountRewardsSettlementDetails);Date beginDate = this.getToday("00:00:00");Date endDate = this.getToday("23:59:59");log.info(beginDate.toString() + " ~ " + endDate.toString());GroupOperation groupOperation = group("loginname").sum("amount").as("amount");MatchOperation matchOperation = match(new Criteria("createdDate").gte(beginDate).lte(endDate));SortOperation sortOperation = sort(new Sort(Direction.ASC, "loginname"));Aggregation aggregation = newAggregation(matchOperation, groupOperation, sortOperation);AggregationResults<MultilevelDirectSellingAccountRewardsSettlementDetails> results = mongoTemplate.aggregate(aggregation, MultilevelDirectSellingAccountRewardsSettlementDetails.class, MultilevelDirectSellingAccountRewardsSettlementDetails.class);		System.out.println(results.getRawResults().get("result").toString());

5.2.4.16.?創建索引

mongoOps.indexOps(User.class).ensureIndex(new Index().on("name", Direction.ASC));

5.2.4.17.?子對象操作

5.2.4.17.1.?List 類型

package cn.netkiller.api.domain;import java.util.List;import javax.persistence.Id;
import org.springframework.data.mongodb.core.mapping.Document;@Document
public class Article {@Idprivate String id;private String title;private String description;List<Author> author;public static class Author {private String id;private String firstname;private String lastname;public Author(String firstname, String lastname) {this.firstname = firstname;this.lastname = lastname;}}
}

更新

db.getCollection('foo').update({"author.firstname":"neo"},{"$set":{"author.$.firstname":"netkiller"}})

更新數據

Query query = Query.query(Criteria.where("author.firstname").is("neo"));Update update = new Update().set("author.$.firstname", "netkiller");mongoTemplate.updateFirst(query, update, Article.class);

追加數據

Query query = Query.query(Criteria.where("id").is("5bbf091efd9557069c4a25c5"));Update update = new Update().push("author", new Author("neo", "chen"));mongoTemplate.updateFirst(query, update, Article.class);

刪除數據

Query query = Query.query(Criteria.where("id").is("5bbf091efd9557069c4a25c5"));Update update = new Update().pull("author", new Author("jerry", "lee"));mongoTemplate.updateFirst(query, update, Article.class);

?

?

?

轉載于:https://my.oschina.net/neochen/blog/2243901

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/450476.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/450476.shtml
英文地址,請注明出處:http://en.pswp.cn/news/450476.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

ZooKeeper原理及使用

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 ZooKeeper是Hadoop Ecosystem中非常重要的組件&#xff0c;它的主要功能是為分布式系統提供一致性協調(Coordination)服務&#xff0c;與…

自律只需要這篇文章

1. 鉆研&#xff0c;只要你有一個方面特別優秀&#xff0c;則在這個社會就足夠了,能夠吃一輩子 2. 領悟&#xff0c;需要的時候&#xff0c;別人給你只是一個具體的方向&#xff0c;具體的路還是要自己去設計 3. 執行力&#xff0c;晚上喜歡想想沒有小本本記錄&#xff0c;那么…

數據和文件操作

怎樣用C語言對某個目錄下的文件名進行排序? 在4&#xff0e;8的例子中&#xff0c;用_dos_findfirst()和_dos_findnext()函數遍歷目錄結構&#xff0c;每找到一個文件名&#xff0c;就把它打印在屏幕上&#xff0c;因此&#xff0c;文件名是逐個被找到并列出來的。當你對某個目…

這些年來什么才是最好的投資?

這些年&#xff0c;就是從我畢業&#xff08;2006&#xff09;以后... 聊投資&#xff0c;不免說股市&#xff1b;股市平時沒什么人談&#xff0c;一般暴漲暴跌時大家的談興就起來了。而最近這一周&#xff0c;全球股市都開啟了暴跌模式&#xff0c;讓投資者虧損慘重&#xff0…

electron安裝比較慢的方法

ELECTRON_MIRROR"https://cdn.npm.taobao.org/dist/electron/" npm install electron

vim 正則非貪婪模式

比如多匹配使用 .* 效果自然是貪婪模式&#xff0c;JS 的非貪婪很簡單&#xff0c;是 .*? 即可&#xff0c;而 vim 不同&#xff0c;語法是 .\{-}&#xff0c;注意 \ 轉義。 轉載于:https://www.cnblogs.com/ZweiZhao/p/10062543.html

循環結構 案例分析

怎樣才能知道循環是否提前結束了 循環通常依賴于一個或多個變量&#xff0c;你可以在循環外檢查這些變量&#xff0c;以確保循環被正確執行。請看下例&#xff1a;int xchar * cp[REQUESTED_BLOCKS]/ * Attempt (in vain, I must add... )toallocate 512 10KB blocks in memory…

工作中常用的但是又容易忽略的問題

個人平時總結 Document 對象 每個載入瀏覽器的 HTML 文檔都會成為 Document 對象。 Document 對象使我們可以從腳本中對 HTML 頁面中的所有元素進行訪問。 提$(document)是一個選擇器&#xff0c;選中的是整個html所有元素的集合示&#xff1a;Document 對象是 Window 對象的一…

JAVA經典面試題匯總(保存這篇就夠了)

一. java基礎篇 1.final 關鍵字的作用? 被 final 修飾的類不可以被繼承。被 final 修飾的方法不可以被重寫。被 final 修飾的變量不可以被改變&#xff0c;如果修飾引用&#xff0c;那么表示引用不可變&#xff0c;引用指向的內容可變。被 final 修飾的方法&#xff0c;JVM …

Angular5 *ngIf 和 hidden 的區別

問題 項目中遇到一個問題&#xff0c;有一個過濾查詢的面板&#xff0c;需要通過一個展開折疊的button&#xff0c;來控制它的show 和 hide。這個面板中&#xff0c;有一個Select 組件&#xff0c;一個 input 查詢輸入框。 原來代碼是&#xff1a; <div class"accordio…

ZooKeeper學習-- Zookeeper簡單介紹

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 一、分布式協調技術 在給大家介紹ZooKeeper之前先來給大家介紹一種技術——分布式協調技術。那么什么是分布式協調技術&#xff1f;那么…

選擇結構 案例分析

C語言goto&#xff0c;longjmp()和setjmp()之間有什么區別 goto語句實現程序執行中的近程跳轉(local jump)&#xff0c;longjmp()和setjmp()函數實現程序執行中的遠程跳轉(nonlocaljump&#xff0c;也叫farjump)。通常你應該避免任何形式的執行中跳轉&#xff0c;因為在程序中…

Python基礎班---第一部分(基礎)---Python基礎知識---第一個Python程序

01. 第一個 HelloPython 程序 1.1 Python 源程序的基本概念 Python 源程序就是一個特殊格式的文本文件&#xff0c;可以使用任意文本編輯軟件做 Python 的開發Python 程序的 文件擴展名 通常都是 .py1.2 演練步驟 在桌面下&#xff0c;新建 Python基礎1 目錄在 Python基礎1 目錄…

面試題-集合

1.JAVA 中數組和集合的區別 &#xff1f; &#xff08;1&#xff09;數組的長度是固定的&#xff0c;而集合長度是可以改變的。 &#xff08;2&#xff09;數組可以儲存基本數據類型和引用數據類型&#xff0c;而集合只能儲存引用數據類型&#xff08;也就是對象&#xff09;…

七牛云上傳視頻如何有效做到節省空間

在上傳視頻的時候&#xff0c;我們通常會保存到第三方【七牛云】平臺。不過大多數程序員在系統后臺上傳視頻后&#xff0c;一般都是保存到了本地&#xff0c;如果視頻非常多或者視頻容量特別大的情況下&#xff0c;那么我們的服務器遲早有一天會滿&#xff0c;為了節省空間&…

運算符的優先級總能起作用嗎?

有關運算符優先級的規則稍微有點復雜。在大多數情況下&#xff0c;這些規則確實是你所需要的&#xff0c;然而&#xff0c;有人也指出其中的一些規則本來是可以設計得更好的。讓我們快速地回顧一些有關內容&#xff1a;“運算符優先級”是這樣一些規則的集合——這些規則規定了…

按鈕交互loading ---- 轉圈圈 加載

按鈕loading狀態自定義選項&#xff08;功能&#xff09;&#xff1a; 可以在元素上添加 data-am-loading 來設置選項&#xff1a; spinner 加載動畫圖標&#xff0c;適用于支持 CSS3 動畫、非 input 元素&#xff0c;寫圖標名稱即可&#xff1b;loadingText 加載時顯示的文字&…

面試題-線程

1.什么是線程 &#xff1f;線程和進程的區別 &#xff1f; 線程是操作系統能夠進行運算調度的最小單位&#xff0c;它被包含在進程之中&#xff0c;是進程中的實際運作單位。而進程是系統中 正在運行的一個程序&#xff0c;程序一旦運行就是進程。 區別&#xff1a;&#xf…

區塊鏈入門教程

前些天發現了一個巨牛的人工智能學習網站&#xff0c;通俗易懂&#xff0c;風趣幽默&#xff0c;忍不住分享一下給大家。點擊跳轉到教程。 區塊鏈&#xff08;blockchain&#xff09;是眼下的大熱門&#xff0c;新聞媒體大量報道&#xff0c;宣稱它將創造未來。 可是&#xf…

響應式面包屑菜單

在線演示 本地下載 轉載于:https://www.cnblogs.com/qixidi/p/10064991.html