如何展平汇总结果

时间:2019-11-15 11:52:39

标签: python mongodb pymongo

MongoDB:3.6 +

我有这个Pymongo / MongoDB查询:

    _data = db['history'].aggregate([
        {'$lookup': 
            {
                'from': 'mgmt_item',
                'localField': 'id_mgmt_item',
                'foreignField' : 'old_id',
                'as': 'mgmt_item'
            }
        },
        {'$match': query},
        {'$project': projection}
    ])

我得到以下结果,这是正确的。

{ 
   "_id":"a4f2a993-749d-4b27-a9bd-c5950babd1bf",
   "id_mgmt_item":3,
   "value":99.660095,
   "image_path":"https://url/a4f2a993-749d-4b27-a9bd-c5950babd1bf.jpg",
   "mgmt_item":[ 
      { 
         "lang":{ 
            "pt_BR":"Descrição..."
         }
      }
   ]
}

但是,我想使结果 flatten 具有 mgmt_item.lang.pt_BR 的值作为 mgmt_item attr的值,如下所示:

{ 
   "_id":"a4f2a993-749d-4b27-a9bd-c5950babd1bf",
   "id_mgmt_item":3,
   "value":99.660095,
   "image_path":"https://url/a4f2a993-749d-4b27-a9bd-c5950babd1bf.jpg",
   "mgmt_item":"Descrição..."
}

我应该在查询中做些什么更改才能获得所需的结果?

1 个答案:

答案 0 :(得分:0)

您可以将以下$ replaceRoot阶段添加到聚合列表的末尾以根据需要进行展平:

  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          "$$ROOT",
          {
            "mgmt_item": {
              $arrayElemAt: [
                "$mgmt_item.lang.pt_BR",
                0
              ]
            }
          },
        ]
      }
    }
  }

游乐场:

https://mongoplayground.net/p/iR8Qoc3TkXU

文档:

https://docs.mongodb.com/manual/reference/operator/aggregation/replaceRoot/

https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt/