I have a collection called 'article' and I need to sort the objects based on the size of the array it contains. What is the most efficient way to achieve this? One option is to retrieve the entire list of objects and manually sort them in JavaScript. However, since I am returning articles 10 at a time, sorting the array every time the API is called seems like unnecessary work.
Article.find({})
.limit(10)
.skip(req.params.page*10)
//Possibly using $project to create a new variable 'votecount' that counts objects in a given array.
.sort({votecount:-1})
.exec(function(err,arts){
articleObj.articles = arts;
if (arts.length<10){
articleObj.reachedEnd = true;
}
res.json(articleObj);
});
I also need to calculate the number of votes received up. Here is an example object:
{
"_id" : ObjectId("55f50cfddcf1ad6931fb8dd4"),
"timestamp" : "2015-09-13T00:58:57-5:00",
"url" : "http://www.nytimes.com/2015/09/13/sports/floyd-mayweather-finishes-bout-and-maybe-his-career-with-lopsided-win-over-andre-berto.html",
"abstract" : "Mayweather’s victory by unanimous decision gave him a record of 49-0, the same as the legendary heavyweight Rocky Marciano.",
"title" : "Mayweather Wins Easily in What He Calls Last Bout",
"section" : "Sports",
"comments" : [ ],
"votes" : {
"up" : [
ObjectId("55e5e16934d355d61c471e48")
],
"down" : [ ]
},
"image" : {
"caption": "Floyd Mayweather Jr. after learning he defeated Andre Berto in a unanimous decision.",
"url": "http://static01.nyt.com/images/2015/09/14/sports/13fight/13fight-mediumThreeByTwo210.jpg"
},
"__v" : 0
}