mongodb 查询问题

SimonAt 发布于 2016/09/29 15:58
阅读 289
收藏 0

字段: appId,  moduleNo, curValue, receiveDate.

数据库中数据例子:

{
  "appId": "appA",
  "moduleNo": 1,
  "curValue" : 21,
  "receiveDate" : ISO(5)
}
{
  "appId": "appA",
  "moduleNo": 1,
  "curValue" : 21,
  "receiveDate" : ISO(4)
}
{
  "appId": "appA",
  "moduleNo": 2,
  "curValue" : 23,
  "receiveDate" : ISO(3)
}
{
  "appId": "appB",
  "moduleNo": 1,
  "curValue" : 24,
  "receiveDate" : ISO(1)
}
{
  "appId": "appB",
  "moduleNo": 2,
  "curValue" : 25,
  "receiveDate" : ISO(2)
}

现在想一次性查询出 appId为  appA, appB,  moduleNo为 1,2 receiveDate 为最新的数据。

就是所有 appId+moduleNo 组合的最新一条数据。

返回结果应该是

{
  "appId": "appA",
  "moduleNo": 1,
  "curValue" : 21,
  "receiveDate" : ISO(5)
}
{
  "appId": "appA",
  "moduleNo": 2,
  "curValue" : 23,
  "receiveDate" : ISO(3)
}
{
  "appId": "appB",
  "moduleNo": 1,
  "curValue" : 24,
  "receiveDate" : ISO(1)
}
{
  "appId": "appB",
  "moduleNo": 2,
  "curValue" : 25,
  "receiveDate" : ISO(2)
}

求mongdodb 上应该怎么实现?






加载中
0
SimonAt
SimonAt

自问自答:

db.iot_run_record.aggregate([

    {
  "$match" : {"collect_item" : {"$in": [52, 51] } , deviceId : {"$in": [ObjectId("57eb7238c520c431942a2f19"), ObjectId("57eb7308c520c431942a2f1b")] } }
    },
    { "$sort": { "deviceId" : 1, "collect_item": 1, "receiveDate":-1 } },  
    { "$group": {
        "_id": { "deviceId": "$deviceId", "collect_item" :"$collect_item" },
        "results": {
            "$push": {
                "deviceId": "$deviceId", 
                "collect_item": "$collect_item",
                "runStatus": "$runStatus",
                "receiveDate": "$receiveDate"
            }
        }
    }},
    { "$project": {
        "results": { "$slice": [ "$results", 1 ] }
    }}
]);


0
SimonAt
SimonAt

或者这样也行:

db.iot_run_record.aggregate([
    {
  "$match" : {"collect_item" : {"$in": [52, 51] } , deviceId : {"$in": [ObjectId("57eb7238c520c431942a2f19"), ObjectId("57eb7308c520c431942a2f1b")] } }
    },
    { "$sort": { "deviceId" : 1, "collect_item": 1, "receiveDate":-1 } },  
    { "$group": {
        "_id": { "deviceId": "$deviceId", "collect_item" :"$collect_item" },
        "runStatus": {"$first" :"$runStatus"} ,
        "deviceId": {"$first" :"$deviceId"} ,
         "collect_item": {"$first" :"$collect_item"} ,
         "receiveDate": {"$first" :"$receiveDate"} ,
    }},
     { "$project": {
        "_id": 0,
        "runStatus": 1,
         "deviceId":1,
         "collect_item":1,
         "receiveDate":1
    }}
]);


0
SimonAt
SimonAt
mongdb 分组, mongodb 分组后, 取第一条, 取头几条,聚合,
返回顶部
顶部