繁体   English   中英

如何在 Pymongo 中对字典数组进行排序?

[英]How do I sort array of dictionaries in Pymongo?

我在users数据库中有这个示例 MongoDB 条目:

{
     _id: xxx,
     name: "name",
     files:[{
          fileName: "test",
          size: 50
          },
          {
          fileName: "test2",
          size: 44
          },
          {
          fileName: "test3",
          size: 120
          }
     ]
}

我正在尝试使用 Pymongo 按大小对文件进行排序。

如何使用aggregate命令对字典进行排序? 换句话说,我希望它到 output 这个,在这种情况下,按降序排列:

[
     {
          fileName: "test3",
          size: 120
     },
     {
          fileName: "test",
          size: 50
     },
     {
          fileName: "test2",
          size: 44
     }
]

我找不到仅获取数组本身并将其转换为 Python 列表的方法,因此我可以在使用 Pymongo 库之外对其进行排序,这就是为什么我正在研究使用 Pymongo 库来完成这项工作.

这是我提出的解决方案。 它完全符合我的需要。

db.users.aggregate([
  {
    "$unwind": "$files"
  },
  {
    "$sort": {
      "files.size": 1
    }
  },
  {
    "$replaceRoot": {
      newRoot: "$files"
    }
  }
])

它正在运行: https://mongoplayground.net/p/4v0m02PsbfQ

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM