我找不到任何地方有这样的记录。默认情况下,find()操作将从头获取记录。我怎么能得到mongodb的最后N条记录?
编辑:我也想返回的结果从最近到最近的顺序,而不是相反。
我找不到任何地方有这样的记录。默认情况下,find()操作将从头获取记录。我怎么能得到mongodb的最后N条记录?
编辑:我也想返回的结果从最近到最近的顺序,而不是相反。
当前回答
使用$slice操作符限制数组元素
GeoLocation.find({},{name: 1, geolocation:{$slice: -5}})
.then((result) => {
res.json(result);
})
.catch((err) => {
res.status(500).json({ success: false, msg: `Something went wrong. ${err}` });
});
其中geolocation是数据数组,从中我们得到最近5条记录。
其他回答
最后一个函数应该是sort,而不是limit。
例子:
db.testcollection.find().limit(3).sort({timestamp:-1});
为了得到最近的N条记录,你可以执行以下查询:
db.yourcollectionname.find({$query: {}, $orderby: {$natural : -1}}).limit(yournumber)
如果你只想要最后一张唱片:
db.yourcollectionname.findOne({$query: {}, $orderby: {$natural : -1}})
注意:您可以使用集合中的一列来代替$natural。
如果你使用MongoDB compass,你可以使用sort field来过滤,
使用.sort()和.limit()
按升序或降序使用Sort,然后使用limit
db.collection.find({}).sort({ any_field: -1 }).limit(last_n_records);
使用$slice操作符限制数组元素
GeoLocation.find({},{name: 1, geolocation:{$slice: -5}})
.then((result) => {
res.json(result);
})
.catch((err) => {
res.status(500).json({ success: false, msg: `Something went wrong. ${err}` });
});
其中geolocation是数据数组,从中我们得到最近5条记录。