4

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

1

4 Answers 4

5

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});
    })
});
Sign up to request clarification or add additional context in comments.

Comments

0
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.

2 Comments

I am getting TypeError: q.exec is not a function. Is there any dependencies I am missing? I am new to nodejs and mongodb
First you need to import your model using "require". var Property = require('../models/property'); You can fetch the record using the variable 'Property'. var q = Property.find().sort({created_at: -1}).limit(1); q.exec(function(err, prop) { if (err) res.send(err); res.json(prop); });
0

Here is the one that I use to sort:

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.