Python MongoDB动态字段创建
我有一个字典要在MongoDB中动态插入 当前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-
"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})
这是否满足您的需要?