遍历嵌套数组并在Pymongo中插入新字段

时间:2018-07-16 09:22:18

标签: python arrays mongodb pymongo

MongoDB的新手,文档似乎没有告诉我我要寻找的东西。

我有一个这样的文件:

{
    "_id" : "5G",
    " dump" : [ 
        {
        "severity" : "B - Major",
        "problemReportId" : "x",
        "groupInCharge" : "test",
        "feature" : null,
        "_id" : "1",
    },
        {
        "severity" : "BM",
        "problemReportId" : "x",
        "groupInCharge" : "test",
        "feature" : null,
        "_id" : "1",
    }, ]
}

转储可以有任何数字的地方... [0,1,2 .... X,Y,Z]

我想输入一个新字段,让我们称它为转储字典中的重复字段,所以它看起来像这样:

{
    "_id" : "5G",
    " dump" : [ 
        {
        "severity" : "B - Major",
        "problemReportId" : "x",
        "groupInCharge" : "test",
        "feature" : null,
        "_id" : "1",
        "duplicate": "0",

    },
        {
        "severity" : "M",
        "problemReportId" : "y",
        "groupInCharge" : "testX",
        "feature" : null,
        "_id" : "1",
        "duplicate": "0",
    }, ]
}

我尝试了下面的代码,但是它所做的只是替换数组,我无法弄清楚如何遍历数组。

    for issue in issues:
    # Adding a field to tell if issue is a duplicate, 1 = Yes. 0 = No.
        duplicate_value = {'dump' : { 'duplicate': 0}}
        _key = {"_id": project}
        db.dump.update (_key, duplicate_value, upsert=True)

2 个答案:

答案 0 :(得分:1)

您可以尝试遵循$map聚合

db.collection.aggregate([
  {
    $project: {
      dump: {
        $map: {
          input: "$dump",
          as: "dp",
          in: {
            "severity": "$$dp.severity",
            "problemReportId": "$$dp.problemReportId",
            "groupInCharge": "$$dp.groupInCharge",
            "feature": "$$dp.feature",
            "_id": "$$dp._id",
            "duplicate": "0"
          }
        }
      }
    }
  }
])

答案 1 :(得分:0)

如果您只需要更新字段,则应使用@Anthony Winzlet建议您使用Mongo的本机运算符来实现它。

但是,如果出于某些原因您确实需要在Python代码中解析和更新数组,我相信使用.save()会更好:

    client = MongoClient(host,port)
    collection = client.collection

    for item in collection.find({ ... }):
        // Do anything you want with the item...
        item["dump"]["duplicate"] = 0
        // This will update the item if the dict has a "_id" field, else will insert as a new doc.
        collection.save(item)