Sorting objects in array within mongodb -
i've seen question on google/so/mongo docs, , i've tried implement solution, it's not working me. have following test database:
> db.test.find().pretty() { "_id" : objectid("56b4ab167db9acd913ce6e07"), "state" : "helloworld", "items" : [ { "guid" : "123" }, { "guid" : "124" }, { "guid" : "123" } ] }
and want sort "guid" element of items. running sort commands yields:
> db.test.find().sort( {"items.guid" : 1}).pretty() { "_id" : objectid("56b4ab167db9acd913ce6e07"), "state" : "helloworld", "items" : [ { "guid" : "123" }, { "guid" : "124" }, { "guid" : "123" } ] }
how can sort "guid" element, returned output of "items" 123, 123, , 124 guids (essentially move child elements of "items" they're sorted "guid")?
edit: i've tried use $orderby
command, doesn't accomplish want:
> db.test.find({ $query : {}, $orderby: {'items.guid' : 1} }).pretty() { "_id" : objectid("56b4ab167db9acd913ce6e07"), "state" : "helloworld", "items" : [ { "guid" : "123" }, { "guid" : "124" }, { "guid" : "123" } ] }
here how can done using aggregate
db.test.aggregate([ { $unwind : '$items' }, { $sort : {'items.guid' : 1} }, { $group : { _id : '$_id', state : {$first : '$state'}, items : { $push : {'guid' : '$items.guid'} } } } ]).pretty()
this output command.
{ "_id" : objectid("56b4ab167db9acd913ce6e07"), "state" : "helloworld", "items" : [ { "guid" : "123" }, { "guid" : "123" }, { "guid" : "124" } ] }
Comments
Post a Comment