mongodb - Locating a specific record in an aggregation of a Mongo DB collection -
i working on reporting project deal monthly orders have orders coming mongodb in below format
order:{ _id: 123456789012123456789012, items:[ {code:'item1', qty:5},{code:'item2', qty:6} ] }
my requirement find out how specific item ranks against other items in on performance
i wrote aggregation first find out grouping of each item , number of quantities ordered
db.orders.aggregate( [ { $unwind : "$items" }, { $group : {code : "$code" , tot_ord: { $sum : "$qty" } } }, { $sort : { tot_ord : -1 } } ] )
so should give me sorted list of items highest orders first.
but how rank of specific item without looping? talking 500,000 different items want avoid looping
thanks in advance.
update: had working. example using node.js. posting useful in future
function aggregate(mongodb,collection_item, pipeline, next){ mongodb.collection(collection_item, function(err, collection) { collection.aggregate(pipeline,function(err,result) { if(err){ console.log('error aggregating: ' + err); next({'error':'an error has occurred - ' + err}); }else{ next(result); } }); }); } function calculateorderrank(itemid){ aggregate(mongodb, "orders", [ { $unwind : "$items" }, { $match : { items.code : itemid} }, { $group : { _id : "$items.code" , tot_qty: { $sum : "$items.qty" } } } ],function(result) { var itemqty = result[0].tot_qty; data.aggregate(mongodb, "orders", [ { $unwind : "$items" }, { $group : { _id : "$items.code" , tot_qty: { $sum : "$items.qty" } } }, { $match: {tot_qty:{$gt:itemqty}} }, { $group : {_id:null, rank : { $sum : 1 } } }, ],function(result) { var rank = 1; if (result && result.length>0) { rank = result[0].rank + 1; } res.send({item_id:itemid, rank:rank, score:itemqty}); }); } ); }
this feature not exist in aggregation framework @ time. need jira.mongodb.org/browse/server-8065 implemented able rankings.
meanwhile can 2 aggregation framework queries.
the first 1 aggregate , totals specific item in question (it similar include in question, $group format incorrect, should {$group: {_id:"$items.code", <etc>}
). start limiting "items.code" particular value.
the second 1 collection , after aggregation {match:{count:{$gt:<count-for-that-one-item>}}
, $group
count how many "totals" higher 1 item's. gives item's rank.
Comments
Post a Comment