如何遍历嵌套数组并使用python在mongodb中插入元素

时间:2017-09-06 12:40:06

标签: python mongodb

我是mongodb的新手,我想遍历一个嵌套的数组文档并在该文档中插入一个新数组。我不确定如何遍历此树结构文档。

这是我的代码:

dataList = {"code": '1', "sensor_name": 'digital',"type": 'rpm'}

db.datapoints.update_one(
                {'sites.areas.lines.line_name': 'Press Line'},
                {"$push": {'sites.areas.lines.resources':[dataList]}}
            )

我现有的文件:

{
  "org_name": "VISION", 
  "org_id": "58d2b48760bfd71bbc7bbf2a", 
  "sites": 
  [
    {
      "site_code": "af2df470-1b97-4763-a80c-f704eefa295a", "site_name": 
      "Office", 
      "areas": 
      [
        {
          "lines": 
          [
            {
              "line_code": "1daed5e5-a4cd-4644-98a1", 
              "line_name": "Line", 
           }, 
           {
              "line_code": "40abea9f-329c",
              "line_name": "Ovens", 
           }
         ], 
         "area_name": "Manufacturing", 
         "area_code": "4a47c299-ff3c-4426-a511"
      }
    ]     
  }
]
}

执行我想要的查询之后:

{
  "org_name": "VISION", 
  "org_id": "58d2b48760bfd71bbc7bbf2a", 
  "sites": 
  [
    {
      "site_code": "af2df470-1b97-4763-a80c-f704eefa295a", "site_name": 
      "Office", 
      "areas": 
      [
        {
          "lines": 
          [
            {
              "line_code": "1daed5e5-a4cd-4644-98a1", 
              "line_name": "Line", 
              "resources": 
              [
                {
                  "code": "1", 
                  "sensor_name": "digital",
                  "type": "rpm"  
                }
             ]    
           }, 
           {
              "line_code": "40abea9f-329c",
              "line_name": "Ovens",
           }
         ], 
         "area_name": "Manufacturing", 
         "area_code": "4a47c299-ff3c-4426-a511"
      }
    ]     
  }
]
}

谁能告诉我怎么做到这一点?我已经坚持这么多个小时了。

0 个答案:

没有答案