user7201227
user7201227

Reputation: 85

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);
}

Upvotes: 0

Views: 5423

Answers (3)

sreehari vr
sreehari vr

Reputation: 1

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

Upvotes: 0

num8er
num8er

Reputation: 19372

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

Upvotes: 6

kailash yogeshwar
kailash yogeshwar

Reputation: 834

Use this query:

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

Upvotes: 5

Related Questions