如何查询以获取Mongoose中的最后更新日期

时间:2015-03-13 09:57:33

标签: node.js mongoose

我有这个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的新手。

1 个答案:

答案 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
})