如何从mongodb中的子文档中获取最高键及其值
我有以下mongo文档,数据子文档包含时间戳的特定分钟的数据。我想为数据子文档提取具有最大值的键。在这种情况下,它将是关键59如何从mongodb中的子文档中获取最高键及其值,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有以下mongo文档,数据子文档包含时间戳的特定分钟的数据。我想为数据子文档提取具有最大值的键。在这种情况下,它将是关键59 { "_id" : ObjectId("565ab6007c7925aae95afd89"), "gatewayId" : NumberInt(12), "timestamp" : "2015-09-21 05:00:00", "data" : { "2" : { "day_chan1" :
{
"_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)
}
}
}
我已经找到了aggregate,但找不到相应的查询。您可以使用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},
})
这使得使用聚合框架成为可能:
db.collection.aggregate([
{$match:{
"_id": ObjectId("565ab6007c7925aae95afd89")
}},
{$unwind: "$data"},
{$sort: {"data.key" : -1}},
{$limit: 1}
])
更改您的文档结构,您会发现相应的查询这是mongodb博客的适当结构谢谢,我已经想到了,但我有点担心,因为我想遵循mongodb博客中规定的模式。
db.collection.aggregate([
{$match:{
"_id": ObjectId("565ab6007c7925aae95afd89")
}},
{$unwind: "$data"},
{$sort: {"data.key" : -1}},
{$limit: 1}
])