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

我有这个mongodb集合。 有两个不同的lastUpdatedate的file1.pkg

 { "_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" } 

我想要得到最新的更新date文件,如:

 { "_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的新手。

您可以使用聚合pipe道来执行此操作:

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