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

本文节选自 《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 对象

@Autowired
	private 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 {

	@Id
	private 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值