我如何使用 Mongoose 获取第二天到最新或前一天的文档集合?
我获取最新数据的代码如下:
data.findOne()
.sort({"_id": -1})
.exec(function(err, data) {
if (err) {
console.log('Error getting data..');
}
if (data) {
res.json(data);
}
else {
console.log('No data found!');
}
});
这仅返回集合中最新的文档。相反,我需要最新的之前的一个,所以前一天的一个,我该如何做到这一点?
最佳答案
那么你必须使用聚合:
db.getCollection('data').aggregate([
{ $sort: {"date": -1}}, // sort by latest date (descending)
{ $limit: 2}, // limit to the first two results
{ $sort: {"date": 1}}, // sort these two ascending
{ $limit: 1} // get first document
])
这个管道是用 Mongoose 翻译的(我认为):
data.aggregate([
{ $sort: {"date": -1}},
{ $limit: 2},
{ $sort: {"date": 1}},
{ $limit: 1}
], function (err, result) {
if (err) {
next(err);
} else {
res.json(result);
}
});
此外,通过在不添加 $match
管道的情况下进行排序,您的第一个 $sort
将对集合中的所有文档进行排序。因此,如果您的集合很大,您可能需要使用一些可以添加到 $match
管道中的查询参数来限制它们。您可以在第一个 $sort
之前添加匹配项
例如
db.getCollection('data').aggregate([
{ $match: {...}},
{ $sort: {"date": -1}},
{ $limit: 2},
{ $sort: {"date": 1}},
{ $limit: 1}
])
关于node.js - Mongoose /MongoDB : Get second to last document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47360383/