《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.mzph.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