在 pymongo 中首先收集两个集合并更新文档

Aggregate across two collections and update documents in first collect in pymongo

我正在使用 pymongo。我有一个集合,我想根据另一个集合的值更新字段。 这是 collection1 中的文档。

{ _id: ObjectId("5fef7a23d0bdc785d4fc94e7"),
  path: 'path1.png',
  type: 'negative',
  xmin: NaN,
  ymin: NaN,
  xmax: NaN,
  ymax: NaN}

来自集合 2:

{ _id: ObjectId("5fef7a24d0bdc785d4fc94e8"),
  path: 'path1.png',
  xmin: 200,
  ymin: 200,
  xmax: 300,
  ymax: 300}

如何更新集合 1 以使示例文档如下所示:

{ _id: ObjectId("5fef7a23d0bdc785d4fc94e7"),
  path: 'path1.png',
  type: 'negative,
  xmin: 200,
  ymin: 200,
  xmax: 300,
  ymax: 300}

将 collection2 提取到 dict 变量中并使用 $set 更新 collection1,例如

for doc in db.collection2.find({}, {'_id': 0}):
    db.collection1.update_one({'path': doc.get('path')}, {'$set': doc})

我找到了一种方法可以将它输出到一个单独的集合中,但仍然不确定如何将它输出到同一个集合中。

db.collection1.aggregate[
    {
        '$match': {
            'xmin': 'NaN'
        }
    }, {
        '$lookup': {
            'from': 'collection2', 
            'localField': 'path', 
            'foreignField': 'path', 
            'as': 'inferences'
        }
    }, {
        '$project': {
            'inferences.xmin': 1, 
            'inferences.ymin': 1, 
            'inferences.xmax': 1, 
            'inferences.ymax': 1, 
            'path': 1,  
            'type': 1, 
            '_id': 0
        }
    }, {
        '$unwind': {
            'path': '$inferences', 
            'preserveNullAndEmptyArrays': False
        }
    }, {
        '$addFields': {
            'xmin': '$inferences.xmin', 
            'ymin': '$inferences.ymin', 
            'xmax': '$inferences.xmax', 
            'ymax': '$inferences.ymax'
        }
    }, {
        '$project': {
            'path': 1, 
            'type': 1, 
            'xmin': 1, 
            'ymin': 1, 
            'xmax': 1, 
            'ymax': 1
        }
    }, {
        '$out': 'collection3'
    }
]