【问题标题】:Sort by count and get parent nodes attributes按计数排序并获取父节点属性
【发布时间】:2020-10-02 05:55:40
【问题描述】:

假设我有这个结构:

{
    "_id": "Henry IV",
    "acts": [
    {
        "_id": "ACT I",
        "scenes": [
        {
            "_id": "SCENE I. London. The palace.",
            "speeches": [
            {
                "_id": 1,
                "speaker": "KING HENRY IV",
                "lines": [
                {
                    "_id": "1.1.1",
                    "text": "So shaken as we are, so wan with care,"
                },
                {
                    "_id": "1.1.2",
                    "text": "Find we a time for frighted peace to pant,"
                },
                {
                    "_id": "1.1.3",
                    "text": "And breathe short-winded accents of new broils"
                }]
            },
            {
                "_id": 2,
                "speaker": "WESTMORELAND",
                "lines": [
                {
                    "_id": "1.1.34",
                    "text": "My liege, this haste was hot in question,"
                },
                {
                    "_id": "1.1.35",
                    "text": "And many limits of the charge set down"
                }]
            }]
        }]
    }]
}

¿如何获得按“行”数排序的结果并具有父节点属性?理想的结果应该是这样的:

{'play': 'Henry IV', 'act': 'ACT I', 'scene': 'SCENE I. London. The palace.', 'speech', '1', 'speaker': 'KING HENRY IV', 'line_count': 3}

{'play': 'Henry IV', 'act': 'ACT I', 'scene': 'SCENE I. London. The palace.', 'speech', '2', 'speaker': 'WESTMORELAND', 'line_count': 2}

【问题讨论】:

    标签: mongodb aggregation-framework pymongo


    【解决方案1】:

    您需要使用$unwind 运算符展平嵌套数组,并使用$project 运算符将其转换为所需的输出,如下所示:

    db.collection.aggregate([
      {
        $unwind: "$acts"
      },
      {
        $unwind: "$acts.scenes"
      },
      {
        $unwind: "$acts.scenes.speeches"
      },
      {
        $project: {
          _id: 0,
          play: "$_id",
          act: "$acts._id",
          scene: "$acts.scenes._id",
          speech: "$acts.scenes.speeches._id",
          speaker: "$acts.scenes.speeches.speaker",
          line_count: {
            $size: "$acts.scenes.speeches.lines"
          }
        }
      },
      //Add here your sorting condition
      {
        $sort: {
          act: 1,
          speech: 1,
          line_count: 1
        }
      }
    ])
    

    MongoPlayground

    注意:如果任何嵌套数组为空,文档将被跳过

    派蒙哥

    from bson.son import SON
    pipeline = [
         {"$unwind": "$acts" },
         ...
         {"$sort": SON([("act", 1), ("speech", 1), ("line_count", 1)])}
    ]
    result = list(db.collection.aggregate(pipeline))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      相关资源
      最近更新 更多