您可以使用在聚合框架的$max
分組功能查找每個group_id
最新的文檔。您需要額外的查詢才能根據分組標準檢索完整文檔。
var results = new Array();
db.groups.aggregate(
// Find documents with latest date for each group_id
{ $group: {
_id: '$group_id',
date: { $max: '$date' },
}},
// Rename _id to group_id, so can use as find criteria
{ $project: {
_id: 0,
group_id:'$_id',
date: '$date'
}}
).result.forEach(function(match) {
// Find matching documents per group and push onto results array
results.push(db.groups.findOne(match));
});
示例結果:
{
"_id" : ObjectId("5096cfb8c24a6fd1a8b68551"),
"group_id" : 1,
"date" : ISODate("2012-11-03T00:00:00Z"),
"foo" : "bar"
}
{
"_id" : ObjectId("5096cfccc24a6fd1a8b68552"),
"group_id" : 2,
"date" : ISODate("2012-11-01T00:00:00Z"),
"foo" : "baz"
}
{
"_id" : ObjectId("5096cfddc24a6fd1a8b68553"),
"group_id" : 3,
"date" : ISODate("2012-11-03T00:00:00Z"),
"foo" : "bat"
}
[?你嘗試過什麼(http://whathaveyoutried.com) – JohnnyHK
我知道這是不太你要找的,但你可以遍歷({group_id:n}).sort({date:-1}).limit(1) - 對於每個group_id = n。通過組ID,執行類似於: db.foo.find 這將按日期對給定組ID的所有文檔進行排序,然後僅返回最近的文檔。 – Louisa