Spring boot 2.0 mongoTemplate 操作范例

1.1. 导入与模板相关的包
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;		
1.2.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");	
1.2.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}*			
1.2.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);			
1.2.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);			
1.2.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);			
1.2.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);			
1.2.7. 删除
User user = new User();
user.setId("5bbf091efd9557069c4a25c5")			
mongoTemplate.remove(user, "user");			
1.2.8. 查找一条数据
public Person findOneByName(String name) {
   Query query = new Query();
   query.addCriteria(Criteria.where("name").is(name));
   return mongoTemplate.findOne(query, Person.class);
}		
1.2.9. 查找所有数据
public List<Person> findByName(String name) {
   Query query = new Query();
   query.addCriteria(Criteria.where("name").is(name));
   return mongoTemplate.find(query, Person.class);
}				
2.0. Query
2.1.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);
}			
2.1.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;
	}
3.0. Criteria
3.1.1. is
Query query = new Query();
query.addCriteria(Criteria.where("name").is("Neo"));
List<User> users = mongoTemplate.find(query, User.class);		
3.1.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);
3.1.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);
3.1.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);
}			
3.1.5. 包含
public List<Person> findByFavoriteBooks(String favoriteBook) {
   Query query = new Query();
   query.addCriteria(Criteria.where("favoriteBooks").in(favoriteBook));
   return mongoTemplate.find(query, Person.class);
}				
4.0. Update
4.1.1. set
Update update = new Update();
update.set("name", "Netkiller");				
4.1.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);				
4.1.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");
4.1.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");				
4.1.5. inc
public void updateMultiplePersonAge() {
   Query query = new Query();
   Update update = new Update().inc("age", 1);
   mongoTemplate.findAndModify(query, update, Person.class);;
}
4.1.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");				
4.1.7. Sort

按照年龄排序

Query query = new Query();
query.with(new Sort(Sort.Direction.ASC, "age"));
List<User> users = mongoTemplate.find(query,User.class);
4.1.8. Query + PageRequest
final Pageable pageableRequest = new PageRequest(0, 2);
Query query = new Query();
query.with(pageableRequest);
4.1.9. 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.0. 创建索引
mongoOps.indexOps(User.class).ensureIndex(new Index().on("name", Direction.ASC));			
5.1.1. 子对象操作
5.1.2. 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);		

TODO.持续更新

你可能感兴趣的:(Java,spring,mongodb)