习惯用mysql的查询语句对mongodb复杂查询有时候力不从心,推荐mongodb聚合查询
db.getCollection("countTurnTableLog")
.aggregate([
{ $match : { $and : [{date : { $gte : 20210201, $lte : 20210222 }}, {behavior : "drawLucky"}]}}, //过滤条件
{ $group: { _id: {user_id:"$userId",date:"$date"}, count: { $sum: 1 } } }, // 分组查询
{$match:{count:{$gt:1}}}, // 分组之后再过滤
{$group:{_id:"$_id.date",count:{$sum:1}}}, //过滤之后再分组
{$sort: {"_id": 1} }//最后再排序
]);
该段mongodb的查询就类似于
select * from (
select count(1),date from countTurnTableLog where date>=20200201 and date <=20200222 and behavior = 'drawLucky'
group by userId,date having count(1)>1) a group by a.date
需求:查询 日期再20210201 到 20210222 时间内,behavior是 drawLucky,按天每天出现两条记录的用户数
内嵌数据查询
1 对查询内嵌数组元素的条件查询:$elemMatch(条件查询所有评论中评论人是:zensss,内容是:dasdsadsadasdsad,的文档)
mongo 查询语句
db.users.find({"comments":{"$elemMatch":{"author" : "zensss","content" :"dasdsadsadasdsad"}}}) .pretty()
java查询语句
Query query4 = new Query(Criteria.where("comments").elemMatch(Criteria.where("author").is("zensss").and("content").is("dasdsadsadasdsad")));
mongoTemplate.find(query4,MongoUser.class,"user");
2 分页查询内嵌数组中的数据
//最新的三条数据
db.users.find({"username":"lison"},{"comments":{"$slice":[0,3]}}).pretty()
//分页查询下一页的数据
db.users.find({"username":"lison"},{"comments":{"$slice":[3,3]},"$id":1}).pretty();
java查询语句
//最新的三条数据
Query query1 = new Query(Criteria.where("username").is("sean"));
query1.fields().include("comments").slice("comments",0,3);
mongoTemplate.find(query1,MongoUser.class,"user");
//分页查询下一页的数据
Query query3 = new Query(Criteria.where("username").is("lison"));
query3.fields().include("comments").slice("comments",3,3).include("id");
mongoTemplate.find(query3,MongoUser.class,"user");