How to sort sub-documents in the array field?

前端 未结 3 650
-上瘾入骨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:17

    It works for me:

    db.getCollection('mycollection').aggregate(
    {$project:{topics:1}},
    {$unwind:"$topics"},
    {$sort :{"topics.words":1}})
    
    0 讨论(0)
  • 2020-12-12 00:21

    MongoDB doesn't provide a way to do this out of the box but there is a workaround which is to update your documents and use the $sort update operator to sort your array.

    db.collection.update_many({}, {"$push": {"topics": {"$each": [], "$sort": {"weight": -1}}}})
    

    You can still use the .aggregate() method like this:

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

    But this is less efficient if all you want is sort your array, and you definitely shouldn't do that.


    You could always do this client side using the .sort or sorted function.

    0 讨论(0)
  • 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"}}}
     ]
    )
    
    0 讨论(0)
提交回复
热议问题