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

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -