How to sort sub-documents in the array field?

随声附和 提交于 2019-12-29 09:14:25

问题


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

{
"_id" : "32022",
"topics" : [
    {
        "weight" : 281.58551703724993,
        "words" : "some words"
    },
    {
        "weight" : 286.6695125796183,
        "words" : "some more words"
    },
    {
        "weight" : 289.8354232846977,
        "words" : "wowz even more wordz"
    },
    {
        "weight" : 305.70093587160807,
        "words" : "WORDZ"
    }]
}

what I want to get is, same structure, but ordered by "topics" : []

{
"_id" : "32022",
"topics" : [
    {
        "weight" : 305.70093587160807,
        "words" : "WORDZ"
    },
    {
        "weight" : 289.8354232846977,
        "words" : "wowz even more wordz"
    },
    {
        "weight" : 286.6695125796183,
        "words" : "some more words"
    },
    {
        "weight" : 281.58551703724993,
        "words" : "some words"
    },
    ]
}

I managed to get some ordered results, but no luck in grouping them by id field. is there a way to do this?


回答1:


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.




回答2:


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"}}}
 ]
)



回答3:


It works for me:

db.getCollection('mycollection').aggregate(
{$project:{topics:1}},
{$unwind:"$topics"},
{$sort :{"topics.words":1}})


来源:https://stackoverflow.com/questions/36875995/how-to-sort-sub-documents-in-the-array-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!