如何根据MongoDB中对象中的值对记录进行排序

发布于 2025-01-24 17:24:35 字数 880 浏览 0 评论 0原文

请考虑以下MongoDB集合

[
    {
        _id: 123123,
        name: "abc"
        topic: {
            asda: "Z"
        }
    },
    {
        _id: 123123,
        name: "abc"
        topic: {
            dasd: "P"
        }
    },{
        _id: 123123,
        name: "abc"
        topic: {
            qwer: "A"
        }
    }
]

根据主题对象中的值进行了查询需求记录(casemensitiationality casemensitiationality ossensitiationality offictial otiven opivent otiven对象)之后,

。注意:主题对象内的密钥将始终是每个记录的不同唯一字符串,

因此结果记录应如下所示

[
    {
        _id: 123123,
        name: "abc"
        topic: {
            qwer: "A"
        }
    },
    {
        _id: 123123,
        name: "abc"
        topic: {
            dasd: "P"
        }
    },{
        _id: 123123,
        name: "abc"
        topic: {
            qwer: "Z"
        }
    }
]

::)

Consider the following MongoDB Collection

[
    {
        _id: 123123,
        name: "abc"
        topic: {
            asda: "Z"
        }
    },
    {
        _id: 123123,
        name: "abc"
        topic: {
            dasd: "P"
        }
    },{
        _id: 123123,
        name: "abc"
        topic: {
            qwer: "A"
        }
    }
]

After performing a query need records sorted(case-insensitively) based on the value inside the topic object.

Note: The key inside the topic object will be always a different and unique string for every record

So the result records should be as follows

[
    {
        _id: 123123,
        name: "abc"
        topic: {
            qwer: "A"
        }
    },
    {
        _id: 123123,
        name: "abc"
        topic: {
            dasd: "P"
        }
    },{
        _id: 123123,
        name: "abc"
        topic: {
            qwer: "Z"
        }
    }
]

Thanks in Advance :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

枫林﹌晚霞¤ 2025-01-31 17:24:35

如果要以未知键的值排序结果,则可以使用$ objectToArray

db.collection.aggregate([
  {
    $addFields: {
      topicArr: {
        $objectToArray: "$topic"
      }
    }
  },
  {
    $sort: {
      "topicArr.v": 1
    }
  },
  {
    $unset: "topicArr"
  }
])

在此游乐场示例

If you want to get the results sorted by the value of an unknown key, you can use $objectToArray

db.collection.aggregate([
  {
    $addFields: {
      topicArr: {
        $objectToArray: "$topic"
      }
    }
  },
  {
    $sort: {
      "topicArr.v": 1
    }
  },
  {
    $unset: "topicArr"
  }
])

As you can see on this playground example

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文