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

Answer

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