我有这个mongodb系列。有两个file1.pkg
具有不同的lastUpdate
日期。
{
"_id" : ObjectId("550286416fee741b0379c2d8"),
"lastUpdate" : ISODate("2015-03-12T16:00:00.000Z"),
"file" : "file1.pkg",
"idBook" : "54f6d1d8c239491400aa495e",
"idUser" : "54c83f37e2e315bfbb43e98a"
},
{
"_id" : ObjectId("450286416fee741e0379c2d8"),
"lastUpdate" : ISODate("2015-03-10T16:00:00.000Z"),
"file" : "file1.pkg",
"idBook" : "54f6d1d8c239491400aa495e",
"idUser" : "54c83f37e2e315bfbb43e98a",
},
{
"_id" : ObjectId("560286416fee741b0379c24d"),
"lastUpdate" : ISODate("2015-03-12T16:00:00.000Z"),
"file" : "file2.pkg",
"idBook" : "54f6d1d8c239491400aa495e",
"idUser" : "54c83f37e2e315bfbb43e98a"
}
我想获取最新更新日期的文件,如:
{
"_id" : ObjectId("550286416fee741b0379c2d8"),
"lastUpdate" : ISODate("2015-03-12T16:00:00.000Z"),
"file" : "file1.pkg",
"idBook" : "54f6d1d8c239491400aa495e",
"idUser" : "54c83f37e2e315bfbb43e98a"
},
{
"_id" : ObjectId("560286416fee741b0379c24d"),
"lastUpdate" : ISODate("2015-03-12T16:00:00.000Z"),
"file" : "file2.pkg",
"idBook" : "54f6d1d8c239491400aa495e",
"idUser" : "54c83f37e2e315bfbb43e98a"
}
如何在 Mongoose 中查询以获得此类结果?我是Mongoose和MongoDB的新手。
答案 0 :(得分:1)
您可以使用aggregation pipeline执行此操作:
MyModel.aggregate([
// Sort the docs by lastUpdate descending to put the newest ones first.
{$sort: {lastUpdate: -1}},
// Group on file, taking the first (newest) doc for each file name.
{$group: {
_id: '$file',
doc: {$first: '$$ROOT'}
}}
], function(err, docs) {
// Reshape the docs array into just the docs.
docs = docs.map(function(doc) {
return doc.doc;
});
// docs contains your desired result
})