简体   繁体   中英

Retrieve last mongodb entry in nodejs

I Need help to retrieve last record from my collection. I have this code:

    db.collection('bbb1collection', function(err, collection) {
    collection.find({}).sort({_id:-1}).limit(1).toArray(function(err, results) {
        path = results;
    console.log(results);
}

使用此查询:

db.users.find().limit(1).sort({$natural:-1})

Check out this:

db.collection('bbb1collection', function(err, collection) {
  collection
    .find()
    .sort({$natural: -1})
    .limit(1)
    .next()
    .then(
      function(doc) {
        console.log(doc);
      },
      function(err) {
        console.log('Error:', err);
      }
    );
});

read about $natural here

 return new Promise(async (resolve, reject) => { db.get().collection('bbb1collection').find().sort({$natural:-1}).limit(1).next().then((res) => { console.log(res) resolve(res) }); });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM