【问题标题】:Aggregate across two collections and update documents in first collect in pymongo在 pymongo 的第一个集合中聚合两个集合并更新文档
【发布时间】:2021-01-03 05:15:17
【问题描述】:

我正在使用 pymongo。我有一个集合,我想根据另一个集合中的值更新字段。 这是收藏中的一份文件1。

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

来自collection2:

{ _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}

【问题讨论】:

    标签: mongodb pymongo


    【解决方案1】:

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

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

    【讨论】:

    • 抱歉,我应该澄清一下,我正在寻找一种解决方案,以类似的方式更新集合 1 中的多个(所有)文档。
    【解决方案2】:

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

    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'
        }
    ]
    

    【讨论】:

      猜你喜欢
      • 2021-07-04
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 2021-06-26
      相关资源
      最近更新 更多