如何在数组字段中对子文档进行排序?

Bed*_*mez 2 mongodb pymongo mongodb-query aggregation-framework

我正在使用MongoDB shell获取一些结果,有序.这是一个采样器,

{
"_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"
    }]
}
Run Code Online (Sandbox Code Playgroud)

我想得到的是,相同的结构,但订购 "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"
    },
    ]
}
Run Code Online (Sandbox Code Playgroud)

我设法获得了一些有序的结果,但没有运气通过id字段对它们进行分组.有没有办法做到这一点?

sty*_*ane 6

MongoDB没有提供开箱即用的方法,但有一种解决方法是更新文档并使用$sortupdate运算符对数组进行排序.

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

你仍然可以使用这样的.aggregate()方法:

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

但是,如果您想要的只是对阵列进行排序,那么效率会降低,而且您绝对不应该这样做.


你总是可以使用.sort或sorted函数来做这个客户端.