Reputation: 164
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
Reputation: 36104
There is no way to do this in find() method,
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);
});
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 ordervar query = ClimateData.aggregate([
{ $match: { device: req.params.device } },
{ $sort: { datetime: -1 } },
{ $limit: 10 },
{ $sort: { datetime: 1 } }
]).exec(function(err, data) {
res.json(data);
});
Upvotes: 3
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
Reputation: 513
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