Shubham Yeole
Shubham Yeole

Reputation: 101

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

Upvotes: 4

Views: 11851

Answers (4)

EladTal
EladTal

Reputation: 2846

From the MongoDb official documentation here:

The order in which you call limit and sort does not matter because the driver reorders the calls to apply the sort first and the limit after it. The following two calls are equivalent:

myColl.find(query).sort({ length: -1 }).limit(3);
myColl.find(query).limit(3).sort({ length: -1 });

You can also apply sort and limit by specifying them in an options object in your call to the find() method. The following two calls are equivalent:

myColl.find(query).sort({ length: -1 }).limit(3);
myColl.find(query, { sort: { length: -1 }, limit: 3 });

Upvotes: 0

Awais-Mohammad
Awais-Mohammad

Reputation: 1

Here is the one that I use to sort:

db.projectadmins.find({}).projection({}).sort({_id:-1}).limit(100)

Upvotes: 0

Stone
Stone

Reputation: 673

var Property = require('../models/property');

var q = Property.find().sort({created_at: -1}).limit(1);
    q.exec(function(err, property) {
        if (err) res.send(err);
        res.json(property);
    });

Can you try this, let me if there is any issue on the result.

Upvotes: 0

Shubham Yeole
Shubham Yeole

Reputation: 101

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

Upvotes: 5

Related Questions