2

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You could use the following:

date = '20140501'
table.find_one_and_update({'id':2}, {'$set': {"value.{}".format(date):23423423}})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.