分組擷取資料:
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 }]
PS:pymongo 在執行function方法的時候,需要引入
from bson.code import Coderun_reduce = Code("function(doc,result){...}")