如何对数组字段中的子文档进行排序? [英] How to sort sub-documents in the array field?

查看:20
本文介绍了如何对数组字段中的子文档进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我想要的是,相同的结构,但按 "topics" 排序:[]

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

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

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

推荐答案

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

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

您仍然可以像这样使用 .aggregate() 方法:

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.

你总是可以使用 .sortsorted 函数.

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

这篇关于如何对数组字段中的子文档进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆