Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use limit in mongodb and NodeJS query

I want to extract only 1 document from mongo db 'property' collection. It should also be the latest document. It looks very simple but I dont know why my query is not retrieving number of document specified in limit.

ORIGINAL METHOD: This query extracts all documents

app.get('/', function(req, res){      
    db.property.find(function (err, docs) {
    res.render("index.ejs",{property: docs});
  })
});

EDIT 1: This query extracts nothing

app.get('/', function(req, res){       
     db.property.find( {sort: {created_at: -1}, limit: 1}, function (err, docs) {
     res.render("index.ejs",{property: docs});
   })
}); 

EDIT 2: This query gives correct 1 document but I want the latest one now.

app.get('/', function(req, res){       
     db.property.find({}).limit(2).toArray(function (err, docs) {
     res.render("index.ejs",{property: docs});
   })
});

Any help would be greatly appreciated.

Thank you

like image 585
Shubham Yeole Avatar asked Oct 23 '25 07:10

Shubham Yeole


1 Answers

I tried modifying query in several ways and finally I got its solution

app.get('/', function(req, res){       
    db.property.find({}).sort({timestamp: -1}).limit(1).toArray(function (err, docs) {
     res.render("index.ejs",{property: docs});
    })
});
like image 150
Shubham Yeole Avatar answered Oct 24 '25 20:10

Shubham Yeole