Mongo Aggregation
I have following documents in my collection { '_id': ObjectId('54490b8104f7142f22ecc97f'), 'title': 'Sample1', 'slug': 'samplenews', 'cat': 'sports',
Solution 1:
Assuming you have the latest version of mongodb installed, one way of doing it is:
Sort
the records based on thepublished_date
in descending order.group
the records based on theircategory
. For each group, collect all the records together in an array.- In the javascript/client side code,
slice
the top 5 records, of each group(category).
The $slice
is not available in the server side $project
aggregation pipeline operator, which holds us from performing the operation on the server side.
var result = db.collection.aggregate(
[
{$sort:{"published_date":-1}},
{$group:{"_id":"$category","values":{$push:"$$ROOT"}}}
]
).map(function(doc){
return {"category":doc._id,"records":doc.values.slice(0,5)};
});
The result
variable will now be an array of documents. Each document representing each category
and in turn having an array of top 5
records.
Solution 2:
You can sort and then limit your request.
$top_five_other = iterator_to_array($db->find(array('category'=>'other')->sort(array('published_date'=>-1))->limit(5));
Solution 3:
you can try aggregate query
1-db.collection.aggregate({ $group : { _id : { category:"$category"}, total : { $sum : 1 }}},{$sort:{_id:1}})
OR
db.collection.aggregate({ $group : { _id : { category:"$category"}, total : { $sum : 1 }}},{$sort:{_id:1}})..forEach( function(myDoc) { print(myDoc._id.category);
})
Post a Comment for "Mongo Aggregation"