2017-04-15 100 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" } } } 
    ] 
)