Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

mongodb - How to sort sub-documents in the array field?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...