mongoDB管道使用-去重分页查询

业务逻辑:查找db.iot_run_record_hist中的数据,其中必须满足一下条件:
	1.runStatus字段取2 , 10 , 18 , 8 , 9 , 17中的一个;
	2.按照deviceId去重,并且重复的数据中取时间最早的一个;
	3.计算每个deviceId重复的数据的数量,记录在count中;
	4.最后的到的数据按照倒序排列,并做分页;


db.iot_run_record_hist.aggregate([
    {
	   "$match" : {"runStatus":{"$in":[2 , 10 , 18 , 8 , 9 , 17]}}
    },
    { "$sort": { "receiveDate":1 } },  
    { "$group": {
        "_id": { "deviceId": "$deviceId" },
        "id":{"$first" :"$_id"},
        "deviceId": {"$first" :"$deviceId"} ,
        "runStatus": {"$first" :"$runStatus"} ,
        "receiveDate": {"$first" :"$receiveDate"},
        "count" : {"$sum" : "$deviceId"}
    }},
    { "$project": {
        "_id": 1,
        "id":1,
        "runStatus": 1,
        "deviceId":1,
        "receiveDate":1,
        "count":1
    }},
    { "$sort": { "receiveDate":-1 } },  
{ "$skip":0 }, { "$limit":10 }
]);
 
  
获取总数目
db.iot_run_record_hist.aggregate([ 
	{ "$match" : {"runStatus":{"$in":[2 , 10 , 18 , 8 , 9 , 17]}} }, 
	{ "$group": { "_id": { "deviceId": "$deviceId", "transportId" : "$transportId"} }}, 
	{ "$group":{"_id":null,"amount":{"$sum":1}}}
]);

 
  
 
  
 
  
 
 

你可能感兴趣的:(mongoDB)