Mischa Binder
Mischa Binder

Reputation: 164

mongoose - getting latest records sorted by date

I currently have the following code:

var query = ClimateData.find({ device: req.params.device })
                       .sort({datetime: -1})
                       .limit(10)
                       .exec(function(err, data) {
                          res.json(data);
                       });

With that being it's possible to get the 10 latest records but starting with the newest. I actually need the date sorted by date so starting with the oldest of the 10 newest records.

Two .sort() calls (as below) did not work. Just got the result that I got 10 records but not the newest.

var query = ClimateData.find({ device: req.params.device })
                       .sort({datetime: -1})
                       .limit(10)
                       .sort({datetime: 1})
                       .exec(function(err, data) {
                          res.json(data);
                       });

Upvotes: 1

Views: 1857

Answers (3)

turivishal
turivishal

Reputation: 36104

There is no way to do this in find() method,

Sort in client side after find() result:

you can do that in your client side programming language (nodejs), like:

var query = ClimateData.find({ device: req.params.device })
.sort({datetime: -1})
.limit(10)
.exec(function(err, data) {
  // SORT FUNCTION
  data.sort((a, b) => a.datetime < b.datetime ? -1 : (a.datetime > b.datetime ? 1 : 0))
  res.json(data);
});

Use aggregate():

or try second option aggregate() method,

  • $match you query condition
  • $sort by datetime in descending order
  • $limit your documents
  • $sort by datetime in ascending order
var query = ClimateData.aggregate([
  { $match: { device: req.params.device } },
  { $sort: { datetime: -1 } },
  { $limit: 10 },
  { $sort: { datetime: 1 } }
]).exec(function(err, data) {
  res.json(data);
});

Playground

Upvotes: 3

Milad Kareem
Milad Kareem

Reputation: 89

Try this:

var query = ClimateData.find({ device: req.params.device })
                       .sort([["_id", 1], ["datetime", -1]])
                       .limit(10)
                       .exec(function(err, data) {
                          res.json(data);
                       });

Upvotes: 0

Dhaval Darji
Dhaval Darji

Reputation: 513

Try like this

var query = ClimateData.find({ device: req.params.device })
                       .sort({datetime: -1,_id:1})
                       .limit(10)
                       .exec(function(err, data) {
                          res.json(data);
                       });

or below

var query = ClimateData.find({ device: req.params.device })
                       .sort({datetime: -1})
                       .limit(10)
                       .sort({_id: 1})
                       .exec(function(err, data) {
                          res.json(data);
                       });

Upvotes: 0

Related Questions