mongodb aggregation using $sum and $sort in mongoid

377 views
Skip to first unread message

Oscar

unread,
Aug 9, 2013, 12:51:46 AM8/9/13
to mon...@googlegroups.com

This code works fine in mongodb shell:

db.orders.aggregate({$unwind: "$picklist"}, {$group : {_id: "$picklist.sku",  qty: {$sum : "$picklist.quantity"}}},{ $sort : { qty : 1}})

I thought conversion to mongoid syntax would look like:

Order.collection.aggregate(
    {'$unwind'=> '$picklist'},
    {'$group'=> {'_id'=> '$picklist.sku',
                 'qty'=> {'$sum'=> '@picklist.quantity'}}},
                { '$sort'=> {'qty'=> -1}})

Then I discovered that $sum and $sort were converted not in a mongoid way. Interesting moment is that I didn't get any errors, it was just giving me zeros for qty.

As for $sum I have to use (as shown here)

.sum(:field_name)

Can't figure out how

 'qty'=> {'$sum'=> '@picklist.quantity'}}},
                    { '$sort'=> {'qty'=> -1}})

should be expressed in a mongoid way.

Posted also on StackOverflow http://stackoverflow.com/q/18139632/1745902

Askar Karasaev

unread,
Aug 9, 2013, 2:37:49 AM8/9/13
to mon...@googlegroups.com
UPDATE: I've tried to do the same operation using mongo driver for ruby and it's giving me the same result, i.e., the value of the qty field for each document resulted from the aggregation is 0. But when I perform aggregation from within mongodb shell it's not zero and has some value depending on the document...


--
 
---
You received this message because you are subscribed to the Google Groups "Mongoid" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mongoid+u...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Askar Karasaev

unread,
Aug 13, 2013, 2:10:56 AM8/13/13
to mon...@googlegroups.com
Solved!

'@picklist.quantity' --> '$picklist.quantity'
Reply all
Reply to author
Forward
0 new messages