如何从mongodb

时间:2015-11-29 09:03:48

标签: mongodb aggregation-framework

我有以下mongo文档,数据子文档包含时间戳的特定分钟的数据。我想提取具有数据子文档的最大值的密钥。在这种情况下,它将是关键59.

{ 
    "_id" : ObjectId("565ab6007c7925aae95afd89"), 
    "gatewayId" : NumberInt(12), 
    "timestamp" : "2015-09-21 05:00:00", 
    "data" : {
        "2" : {
            "day_chan1" : NumberInt(11), 
            "day_chan2" : NumberInt(11), 
            "day_chan3" : NumberInt(7)
        }, 
         "58" : {
            "day_chan1" : NumberInt(642), 
            "day_chan2" : NumberInt(635), 
            "day_chan3" : NumberInt(427)
        }, 
        "59" : {
            "day_chan1" : NumberInt(653), 
            "day_chan2" : NumberInt(647), 
            "day_chan3" : NumberInt(434)
        }
    }
}

我有聚合但无法找到适当的查询。

1 个答案:

答案 0 :(得分:0)

您可以使用map-reduce。

db.runCommand({
    "mapreduce" : "collection",
    "query": {"_id" : ObjectId("565ab6007c7925aae95afd89")},
    "map" : function() {
        maxKey = null;
        for(var k in this.data) { 
            if(maxKey == null || maxKey < k){
                maxKey = k
            }
        }
        emit(maxKey, this.data[maxKey]);
    },
    "reduce" : function(key, stuff) {
        return {key: stuff};
    }, 
    "out": {inline : 1},
})

但是,我同意 user3100115 的评论 - 您可以通过将数据结构更改为以下内容来获得更好的服务:

{ 
    "_id" : ObjectId("565ab6007c7925aae95afd89"), 
    "gatewayId" : NumberInt(12), 
    "timestamp" : "2015-09-21 05:00:00", 
    "data" : [
        {
            "key": 2,
            "day_chan1" : NumberInt(11), 
            "day_chan2" : NumberInt(11), 
            "day_chan3" : NumberInt(7)
        }, 
        {
            "key": 58,
            "day_chan1" : NumberInt(642), 
            "day_chan2" : NumberInt(635), 
            "day_chan3" : NumberInt(427)
        }, 
        {
            "key": 59,
            "day_chan1" : NumberInt(653), 
            "day_chan2" : NumberInt(647), 
            "day_chan3" : NumberInt(434)
        }
    ]
}

这使得可以使用聚合框架:

db.collection.aggregate([
    {$match:{
       "_id": ObjectId("565ab6007c7925aae95afd89")
    }},
    {$unwind: "$data"},
    {$sort: {"data.key" : -1}},
    {$limit: 1}
])