{
"_id" : "1111111",
"userId" : "1",
"userName" : "校长",
"userIds" : [
"1",
"2"
]
"userList" : [
{
"userId":"1",
"userName":"小红"
},
{
"userId":"2",
"userName":"小强"
}
]
}
or查询
final Query query = new Query();
query.addCriteria(new Criteria().orOperator(Criteria.where("isPushAll").is(1),Criteria.where("stuList.id").is(userId)));
long count = mongoTemplate.count(query, User.class);
时间范围搜索(这里时间是date类型,要保持一致,否则查询不到)
final Query query = new Query();
query.addCriteria(Criteria.where("createTime").gte(startDate).lte(endDate);
long count = mongoTemplate.count(query, User.class);
主键查询
this.mongoTemplate.findById("1",User.class);
条件查询
final Query query = new Query();
query .addCriteria(new Criteria("userId").is("1"));
this.mongoTemplate.find(query, User.class);
分页
final Query query = new Query();
query.skip((curPage - 1) * pageSize).limit(pageSize);
//query.with(PageRequest.of(curPage - 1, pageSize, Sort.by(Sort.Order.desc("createTime"))));
this.mongoTemplate.find(query, User.class);
修改
Update update = new Update();
update.set("userName", "张三");
Query query = new Query();
query.addCriteria(new Criteria("userId").is("1"));
mongoTemplate.upsert(query,update,User.class);
集合字段:新增
Update update = new Update();
//字符串集合新增
update.addToSet("userIds", "3");
Query query = new Query();
query.addCriteria(new Criteria("userId").is("1"));
mongoTemplate.upsert(query, update, User.class);
集合字段:修改
Update update = new Update();
//修改字符串集合中指定数据:3 改为 4
update.set("userIds.$","4");
//修改对象集合中指定字段数据:小红 改为 大红
update.set("userIds.$.userName","大红");
//顺便改个名字
update.set("userName", "张三");
Query query = new Query();
query.addCriteria(new Criteria("userId").is("1").and("userIds").is("3"));
mongoTemplate.upsert(query, update, User.class);
集合字段:删除
Update update = new Update();
//删除字符串集合中指定数据:4
update.unset("userIds.$");
//顺便改个名字
update.set("userName", "张三");
Query query = new Query();
query.addCriteria(new Criteria("userId").is("1").and("userIds").is("4"));
mongoTemplate.upsert(query, update, User.class);
注意:update.unset这种方法有一个缺陷,会将符合条件的数据修改成null,如果要彻底删除,则需要使用pull
(pull删除内嵌对象的时候,user对象的值一定要和被删除的一模一样)
Query query = Query.query(Criteria.where("userId").is("1"));
User user= new User ("2","小强");
Update update = new Update();
update.pull("userList", user);
mongoTemplate.updateFirst(query, update, User.class);