我有一个要在MongoDB中动态插入的字典。
当前的MongoDB文档-
"Customers":{
"Payment":{
"CustomerDetails":{
"Source":"Visa Card",
"Name" :"John",
}
}
}
我正在尝试通过python字典对象插入的文档-
final= {"CustomerPayable":["Month":"Feb-1FN-2018","Details":
["Code":"ghg23","AmtPayable": "123.00"]]}
我正在尝试的查询-
db.collection.update({"UserID":UserID},{ '$push':{
'Customers.Payment.Output':final}})
我希望通过上面的查询创建“输出”的动态字段。预期产量-
"Customers":{
"Payment":{
"CustomerDetails":{
"Source":"Visa Card",
"Name" :"John",
},
"Output":{"CustomerPayable":["Month":"Feb-1FN-2018",Details:
["Code":"ghg23","AmtPayable": "123.00"]]}
}
}
任何帮助都很棒。谢谢!
答案 0 :(得分:0)
以下代码应能达到您想要的结果。
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
上进行查询无论如何,我希望这会有所帮助。