How to sort sub-documents in the array field?

前端 未结 3 651
-上瘾入骨i
-上瘾入骨i 2020-12-11 23:47

I\'m using the MongoDB shell to fetch some results, ordered. Here\'s a sampler,

{
\"_id\" : \"32022\",
\"topics\" : [
    {
        \"weight\" : 281.58551703         


        
3条回答
  •  無奈伤痛
    2020-12-12 00:34

    If you don't want to update but only get documents, you can use the following query

     db.test.aggregate(
     [
       {$unwind : "$topics"},
       {$sort : {"topics.weight":-1}},
       {"$group": {"_id": "$_id", "topics": {"$push": "$topics"}}}
     ]
    )
    

提交回复
热议问题