Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python MongoDB动态字段创建_Python_Json_Mongodb - Fatal编程技术网

Python MongoDB动态字段创建

Python MongoDB动态字段创建,python,json,mongodb,Python,Json,Mongodb,我有一个字典要在MongoDB中动态插入 当前MongoDB文档- "Customers":{ "Payment":{ "CustomerDetails":{ "Source":"Visa Card", "Name" :"John", } } } 我试图通过python dictionary对象插入的文档- final= {"CustomerPayable":["Month":"Feb-1FN-

我有一个字典要在MongoDB中动态插入

当前MongoDB文档-

"Customers":{
    "Payment":{
        "CustomerDetails":{
           "Source":"Visa Card",
           "Name" :"John",
       }
    }
}
我试图通过python dictionary对象插入的文档-

    final=  {"CustomerPayable":["Month":"Feb-1FN-2018","Details":
["Code":"ghg23","AmtPayable": "123.00"]]}
我正在尝试的问题-

 db.collection.update({"UserID":UserID},{ '$push':{    
    'Customers.Payment.Output':final}})
我希望通过上述查询创建“Output”的动态字段。预期产量-

 "Customers":{
        "Payment":{
            "CustomerDetails":{
               "Source":"Visa Card",
               "Name" :"John",
           },
          "Output":{"CustomerPayable":["Month":"Feb-1FN-2018",Details:
    ["Code":"ghg23","AmtPayable": "123.00"]]}
        }
    }

任何帮助都很好。请提前感谢

以下代码应能达到您的预期效果

from pymongo import MongoClient

client = MongoClient()
db = client.stackoverflow
collection = db.stackoverflow

a = {"Customers":{ "Payment":{ "CustomerDetails":{ "Source":"Visa Card", "Name" :"John"}}}}
collection.insert(a)

# Prints object before update.
cur = collection.find_one({"Customers.Payment.CustomerDetails.Name":"John"})
print(cur)


final = {"CustomerPayable":{"Month":"Feb-1FN-2018","Details":
                           {"Code":"ghg23","AmtPayable": "123.00"}}}

collection.update({"Customers.Payment.CustomerDetails.Name":"John"},
                  {'$push':{'Customers.Payment.Output':final}})

# Prints object after update.
cur = collection.find_one({"Customers.Payment.CustomerDetails.Name":"John"})
print(cur)
您的代码有两个错误:

  • final
    声明中,您试图在列表中使用字典语法
  • 在更新查询中,您没有名为
    UserID
    的字段,因为我将其更改为查询
    Name

  • 无论如何,我希望这会有所帮助。

    您最好使用db模型来处理$push将数据插入数组。请使用$set
    db.collection.update({“UserID”:UserID},{“$set”:{“Customers.Payment.Output”:final})
    这是否满足您的需要?