我正在尝试获取此数组上的最后一个值(最新更新),但是下面的代码仅返回所有最后一个对象。如果将限制增加到5,我得到2个苹果2个香蕉1个樱桃。我只需要所有的最后一个值。我有20种水果,有150多种产品。我需要选择20种水果的最新值。 谢谢您的帮助。
const last_finder = function (collectionName) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db(dbName);
dbo.collection(collectionName).find({}, {sort:{_id:-1}}).limit(1).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
}
The result:
{
_id: 0,
date: ' 01:30:51',
name: 'Banana',
value: '3.9'
},
{
_id: 1,
date: ' 01:33:51',
name: 'Apple',
value: '2.45'
},
{
_id: 2,
date: ' 01:34:50',
name: 'Banana',
value: '3.8'
},
{
_id: 3,
date: ' 01:34:59',
name: 'Cherry',
value: '6.21'
},
{
_id: 4,
date: ' 01:40:50',
name: 'Apple',
value: '2.55'
}
]
答案 0 :(得分:0)
猫鼬在限制和偏移时有点奇怪,在限制之后需要一个exec函数,
dbo.collection(collectionName).find({}, {sort:{_id:-1}}).limit(1).exec(function(e, data){
console.log(data)
});