Mongodb: sort documents by array objects

前端 未结 4 472
遇见更好的自我
遇见更好的自我 2021-01-03 23:40

I would like to return the documents in an order sorted by which holds the lowest foo.bar value (which are array objects).

I can do db.collection

4条回答
  •  执念已碎
    2021-01-04 00:22

    You can do such a sort with aggregate command from mongo version 2.2:

        db.collection.aggregate([{$unwind: "$foo"},
        {$project: {bars:"$foo.bar"}},
        {$group: {_id:"$_id",min:{$min: "$bars"}}},
        {$sort: {min:1}}])
    

提交回复
热议问题