在MongoDB中对嵌套数组进行排序

时间:2019-10-08 18:04:34

标签: python mongodb sorting nested pymongo

我在mongodb集合中具有以下结构,如下图所示: enter image description here

我将有一个索引号,在其中将有记录,现在记录将是一个或多个数组,如上所示。 我想对数学主题中每个分数的记录中的数据进行排序。 做这个的最好方式是什么? 谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用unwind聚合

    db.collection.aggregate([
       {
          $unwind:{
             path: "$Records",
             includeArrayIndex:"firstUnwind"
         }
       },
       {
          $unwind:{
             path: "$Records",
         }
       },
      { $sort : { Match: -1} },
      {
          $group: {
             _id: {
                id: "$_id",
                firstUnwind: "firstUnwind"
             },
             Index_Number: {$first: "$Index_Number"},
             Records: {$push: "$Records"}
          }
      },
      {
          $group: {
            _id: "$_id.id",
             Index_Number: {$first: "$Index_Number"},
             Records: {$push: "$Records"}
          }
      }
    ])`