繁体   English   中英

如何在 MongoDB 中的嵌入式数组 object 中插入 json object?

[英]How to insert a json object inside embedded array object in MongoDB?

我在 MongoDB 中存储了以下文档:

{
    "_id": 2,
    "template_name": "AllahabadBank",
    "description": "Form For NewCustomer Application In Banking System",
    "handwritten": "true",
    "file_path": "./serverData/batchProcessedFiles/AllahabadBank/input",
    "annotated_data": [{
        "page_num": "page-01.jpg",
        "entities": [{
            "label": "CIFNo",
            "type": "text",
            "boundary_box": {
                "x1": 325,
                "x2": 861,
                "y1": 324,
                "y2": 360
            }
        }],
    "num_of_pages": 12
  }]
}

并希望将以下 JSON 数据插入到annotated_data 建议我 MongoDB 查询或 Python 代码来执行此操作。

{
  "page_num": "page-02.jpg",
  "entities": [
    {
      "label": "CustomerName",
      "type": "text",
      "boundary_box": {
        "x1": 559,
        "x2": 1615,
        "y1": 382,
        "y2": 440
      }
    }
  ]
}

这可以使用更新查询来完成。 下面是使用 pymongo 更新它的 python 代码。 将 __ colName __ 替换为您的列名称。

__colName__.update({'_id':2},
            {'$push':{'annotated_data':{"page_num": "page-02.jpg",
        "entities": [{
            "label": "CustomerName",
            "type": "text",
            "boundary_box": {
                "x1": 559,
                "x2": 1615,
                "y1": 382,
                "y2": 440
            }
        }]
    }}})

上面的Mongo命令如下:

db.__colName__.update({'_id':2},
            {'$push':{'annotated_data':{"page_num": "page-02.jpg",
        "entities": [{
            "label": "CustomerName",
            "type": "text",
            "boundary_box": {
                "x1": 559,
                "x2": 1615,
                "y1": 382,
                "y2": 440
            }
        }]
    }}})

你可以通过两种方式做到这一点:

1)MongoDB更新方法

db.collection.update({"_id":2},
  {
  $push: {
    "annotated_data": {
      "page_num": "page-02.jpg",
      "entities": [
        {
          "label": "CustomerName",
          "type": "text",
          "boundary_box": {
            "x1": 559,
            "x2": 1615,
            "y1": 382,
            "y2": 440
          }
        }
      ]
    }
  }
})

2) 将文档和append检索到数组中(Python 代码)

doc = db.collection.find_one({'_id':2})
doc["annotated_data"].append({
  "page_num": "page-02.jpg",
  "entities": [
     {
       "label": "CustomerName",
       "type": "text",
       "boundary_box": {
          "x1": 559,
          "x2": 1615,
          "y1": 382,
          "y2": 440
       }
    }
  ]
})
db.collection.save(doc)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM