Reputation: 788
data in "test":
{ "_id" : ObjectId("55ddabe6855a0a250877cc92"), "id" : 2, "value" : { "20140501" : 10, "20140502" : 1, "20140503" : 2 }}
I can update in mongodb by this:
db.test.update({id:2}, {$set:{'value.20140501':12}})
But when I use python, I can't be sure this key('20140501').I want to use variable to replace '20140501'.
client = pymongo.MongoClient("localhost", 27017)
db = client.test
table = db.test
date = '20140501'
table.find_one_and_update({'id':2}, {'$set': {"value.date":23423423}})
This is just not right.How to use variable in mongodb with python?
Upvotes: 2
Views: 1179
Reputation: 50416
Python dict manipulation is basically the same as JavaScript, as used in your current notation it "stringifies".
Do this instead:
client = pymongo.MongoClient("localhost", 27017)
db = client.test
table = db.test
date = '20140501'
update = { "$set": {} }
update['$set']['value.' + date] = 23423423
table.find_one_and_update({'id':2}, update)
Now the update
object looks just like you want with the variable replaced in the key.
Upvotes: 1
Reputation: 591
You could use the following:
date = '20140501'
table.find_one_and_update({'id':2}, {'$set': {"value.{}".format(date):23423423}})
Upvotes: 0