2017-04-15 102 views
0

假设在蒙戈DB有这些假文件:

{ 
    "_id" : ObjectId("58f24f38e5fe51fa52e3a90c"), 
    "ref" : "r1", 
    "ts" : 1492275000121 
} 
{ 
    "_id" : ObjectId("58f24f54e5fe51fa52e3a90d"), 
    "ref" : "r1", 
    "ts" : 1492275028031 
} 
{ 
    "_id" : ObjectId("58f24f5ce5fe51fa52e3a90e"), 
    "ref" : "r2", 
    "ts" : 1492275036560 
} 
{ 
    "_id" : ObjectId("58f24f62e5fe51fa52e3a90f"), 
    "ref" : "r3", 
    "ts" : 1492275042696 
} 
{ 
    "_id" : ObjectId("58f24f64e5fe51fa52e3a910"), 
    "ref" : "r2", 
    "ts" : 1492275044864 
} 
{ 
    "_id" : ObjectId("58f24f69e5fe51fa52e3a911"), 
    "ref" : "r1", 
    "ts" : 1492275049360 
} 
{ 
    "_id" : ObjectId("58f24f6be5fe51fa52e3a912"), 
    "ref" : "r3", 
    "ts" : 1492275051880 
} 
{ 
    "_id" : ObjectId("58f24f6ee5fe51fa52e3a913"), 
    "ref" : "r3", 
    "ts" : 1492275054512 
} 
{ 
    "_id" : ObjectId("58f24f70e5fe51fa52e3a914"), 
    "ref" : "r2", 
    "ts" : 1492275056344 
} 

我想实现的是得到的文件列表,其中对于具有最新的时间戳(ts)各ref

喜欢的东西:

  • 得到的所有文件,其中ref["r1", "r2"]
  • 集团这些文件由ref
  • 为每个组根据ts

我希望返回最新文档:

[ 
    { 
     "ref":"r1", 
     "ts": 1492275049360 
    },{ 
     "ref":"r2", 
     "ts": 1492275056344 
    } 
] 

我可以使用单个数据库请求执行此操作吗?我查看了聚合函数,但找不到获取组的最新文档的方法。

回答

1

您可以使用$sort通过ts desc然后$first$group

db.collection.aggregate(
    [ 
    { $match: { ref: { $in: ["r1", "r2"] } } }, 
    { $sort: { ts: -1 } }, 
    { $group: { _id: "$ref", ts: { $first: "$ts" } } } 
    ] 
)