如何查询以获取Mongoose中的最后更新date
我有这个mongodb集合。 有两个不同的lastUpdate
date的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 })
- mongooseerror handling
- 我更好地分裂一个精心制作的mongoose模型?
- 使用javascript / node.js在mongodb中查找带有另一个条件的对象的最早date
- Mongoose / Express / Nodejs尝试从服务器传递一个variables到html
- CastError:投射到ObjectId失败的值“types:”缓冲区“”
- 在mongoose中定义数组的首选方法是什么?
- nodejs / mongoose:连接到使用副本集的数据库
- 没有连接事件正在被解雇 – Mongoose 4.7.1&Express
- MongoDB,Mongoose和Node.js 为什么要申报一个模型?