分组获取数据:
db.express_info.group({ "key":{"express_code":true}, "initial":{"num":"0","mobile":"0"}, "reduce":function(doc,result){result.num++, result.mobile=doc.mobile}, "condition":{"mobile":"18663930231"},"finalize":function(result){result.is_push=result.num+1}})
分析:
key:分组使用的列
initial:设置初始返回元素
reduce:doc 是集合中的文档,result是initial的初始
condition:查询条件
finalize:在返回结果之前处理group的数据文档
返回数据:
[
{
"express_code" : "538419969049",
"num" : 17,
"mobile" : "18663930231",
"is_push" : 18
}
]
管道分组排序分页:
db.express_info.aggregate([{$match:{"mobile":"18663930231"}},{$group : {_id : "$express_code",date_time:{$first:"$datetime"},express_code:{$first:"$express_code"}, num_tutorial : {$sum : 1}}},{$sort:{"datetime":-1}},{$skip:5},{$limit:5}])
分析:
match:查询条件
group:分组
_id:分组条件
datetime:获取组内第一条数据的datetime,express_code 同理
num_tutorial:附加内容,用于统计组内数据量
sort:排序
skip:跳过多少条
limit:限制条数。
返回数据:
[
{ "_id" : "538419968955", "date_time" : "2018-01-15 14:33:44", "express_code" : "538419968955", "num_tutorial" : 17 }
{ "_id" : "812691219127", "date_time" : "2018-01-16 16:17:57", "express_code" : "812691219127", "num_tutorial" : 7 }
{ "_id" : "123123123123", "date_time" : "2018-01-25 14:42:37", "express_code" : "123123123123", "num_tutorial" : 1 }
原文地址:https://www.cnblogs.com/yucongblog/p/10266050.html