一、查询单个文档
@Data
//@Document是spring Data mongodb提供的一个注解。注解指定了这个模型类型所对应的集合名称。
@Document(collection = "information_tag")
public class InformationTag {
}
Query query = Query.query(Criteria.where("articleId").is(id.toString()));
InformationTag tag = mongoTemplate.findOne(query, InformationTag.class, ConstantUtils.ARTICLE_TAG);
二、查询所有文档
Pattern pattern = Pattern.compile("^.*222$",Pattern.CASE_INSENSITIVE);
Criteria criteria = new Criteria();
//phone以222结尾的 或者 name以222结尾的
criteria.orOperator(Criteria.where("phone").regex(pattern),
Criteria.where("name").regex(pattern));
//同时满足 phone以222结尾的,和name以222结尾的
criteria.andOperator(Criteria.where("phone").regex(pattern),
Criteria.where("name").regex(pattern));
Query query = new Query(criteria);
List informationTag s = mongoTemplate.find(query, InformationTag.class);
三、修改文档
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(1)); //_id区分引号 "1"和1
Update update = Update.update();
update.set("name", "zzzzz");
//WriteResult upsert = mongoTemplate.updateMulti(query, update, "userList"); //查询到的全部更新
//WriteResult upsert = mongoTemplate.updateFirst(query, update, "userList"); //查询更新第一条
WriteResult upsert = mongoTemplate.upsert(query, update, "userList"); //有则更新update的字段值;没有则新增, 将Query和Update 的字段值,新增文档
四、操作内嵌文档
例子:
{
"_id" : "195861",
"tags" : [
{
"tagId" : NumberLong(766),
"optDate" : ISODate("2013-08-12T15:21:02.930Z"),
"enable" : true
},
{
"tagId" : NumberLong(778),
"optDate" : ISODate("2013-08-12T15:21:02.930Z"),
"enable" : true
}
]
}
/**
**给tags数组添加一个元素
*/
Tag tag = new Tag(tagId);
tag.setOptDate(new Date());
tag.setEnable(true);
Query query = Query.query(Criteria.where("_id").is(id));
Update update = new Update();
update.addToSet("tags", tag);
mongoTemplate.upsert(query, update, User.class);
/**
**修改tags数组中内嵌文档指定一个元素的值
*/
Query query = Query.query(Criteria.where("_id").is(id)
.and("tags.tagId").is(tagId));
Update update = new Update();
update.set("tags.$.enable", false);
mongoTemplate.updateFirst(query, update, User.class);
/**
**删除tags数组中指定的内嵌文档
*/
Query query = Query.query(Criteria.where("_id").is(id)
.and("tags.tagId").is(tagId));
Update update = new Update();
update.unset("tags.$");
mongoTemplate.updateFirst(query, update, User.class);
update.unset这种方法有一个缺陷,会将符合条件的数据修改成null,如果要彻底删除,则需要使用pull(pull删除内嵌文档的时候,student对象的值一定要和被删除的一模一样)
Query query = Query.query(Criteria.where("classId").is("1"));
Update update = new Update();
Student student = new Student("2","lisi",18,"man");
update.pull("Students",student);
mongoTemplate.updateFirst(query, update, "class");
pull方式删除内嵌文档中的行:
Query query = Query.query(Criteria.where("_id").is(id));
BasicDBObject s = new BasicDBObject();
s.put("tagId", tagid);
Update update = new Update();
update.pull("tags", s);
mongoTemplate.updateFirst(query, update, User.class);
嵌套对象的查询:
这里需要注意下,如果返回的数据列表是整个对象(外对象+内嵌对象)时,内嵌对象的所有行都会被返回,只有返回值对象指定为内嵌对象时,才能过滤掉内嵌对象集合中不符合条件的记录。
db.getCollection('tz_member').find({"memberPhotos.memberId":'4'},{"memberPhotos.$":1}).pretty();
db.getCollection('tz_member').find({"member_id":"3","memberPhotos.memberId":{'$in':['4']}},{"memberPhotos.$":1}).pretty();
五、分页查询
List pipeline = new ArrayList<>();
// $unwind 将数组中的每一个元素转为每一条文档
DBObject unwind = new BasicDBObject();
unwind.put("$unwind", "$contactInfo.followedUsers");
pipeline.add(unwind);
//过滤条件
DBObject condition = new BasicDBObject();
condition.put("uuid", uuid);
//模糊查询
Pattern pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
condition.put("contactInfo.externalContact.name", new BasicDBObject("$regex", pattern));
condition.put("contactInfo.externalContact.externalUserId", new BasicDBObject("$in", externalUserIdList));
DBObject match = new BasicDBObject();
match.put("$match", condition);
pipeline.add(match);
//倒序查询
pipeline.add(new BasicDBObject("$sort", new BasicDBObject("contactInfo.followedUsers.createTime", -1)));
//查询总数
List countPipeline = new ArrayList<>();
//分组条件
DBObject groupFields1 = new BasicDBObject();
groupFields1.put("_id", null);
groupFields1.put("count", new BasicDBObject("$sum", 1));
DBObject group1 = new BasicDBObject("$group", groupFields1);
countPipeline.add(unwind);
countPipeline.add(match);
countPipeline.add(group1);
Cursor output = bigDataMongoTemplate.getCollection("external_contact_info").
aggregate(countPipeline, AggregationOptions.builder().outputMode(AggregationOptions.OutputMode.CURSOR).build());
int count = 0;
while (output.hasNext()) {
BSONObject obj = output.next();
count += (int) obj.get("count");
}
if (page != null) {
page.setTotal(count);
//添加分页
DBObject skipField = new BasicDBObject("$skip", (page.getCurrent() - 1) * page.getSize());
DBObject limitField = new BasicDBObject("$limit", page.getSize());
pipeline.add(skipField);
pipeline.add(limitField);
}
List listVOS = new ArrayList<>();
output = bigDataMongoTemplate.getCollection("helper_external_contact_info").
aggregate(pipeline, AggregationOptions.builder().outputMode(AggregationOptions.OutputMode.CURSOR).build());
while (output.hasNext()) {
BSONObject obj = output.next();
String toJSon = JacksonUtil.toJSon(obj.get("contactInfo"));
ExternalContactInfo externalContactInfo = JSONObject.parseObject(toJSon, ExternalContactInfo.class);
listVOS.add(vo);
}
mongodb 语句:
// 查询总数
db.helper_external_contact_info.aggregate([{"$unwind":"$contactInfo.followedUsers"},
{"$match":{"uuid": "gdshhfjj454j54f5j45", "contactInfo.externalContact.name": {"$regex":"^.*一路.*$"}, "contactInfo.externalContact.externalUserId": {"$in": ["gd55, f54"]} } },
{"$group":{"_id": null, "count": {$sum: 1} } }
])
//查询数据
db.helper_external_contact_info.aggregate([{"$unwind":"$contactInfo.followedUsers"},
{"$match":{"uuid": "6e85df7044fb4bcfc634ebda3c1b52ce", "contactInfo.externalContact.name": {"$regex":"^.*一路.*$"}, "contactInfo.externalContact.externalUserId": {"$in": ["gd55, f54"]} } },
{"$sort": {"contactInfo.followedUsers.createTime": -1 } }
//$and: [{
$or: [{
action: ""
}, {
action: "REPORTED_BEGIN"
}, {
action: {
$exists: false
}
}]
}]
insertTime:{
"$gte":NumberLong(1554048000000),
"$lte":NumberLong(1571328000000)
}