问题
My documents look like this:
{
a: "..."
subdocs [
{
l: "..."
m: "..."
n: 0
},
{
l: "..."
m: "..."
n: 0
}
}
}
I have to update the 'n' field in a particular subdoc using pymongo. I have the document and the index of the subdocument so I can get the subdoc like this
subdoc = mydoc['subdocs'][index]
I try to do an update through pymongo
coll.update( { mydoc['subdocs'][index] : subdoc }, { "$inc": { n: 1 }} )
I get this exception
<type 'exceptions.TypeError'>
I've tried several variations on this and can't get the pymongo syntax right. I think my query document is incorrect. What does pymongo expect for this syntax?
回答1:
You need to identify the array element to update in the second parameter to update
using dot notation like this:
coll.update({'_id': mydoc['_id']}, {'$inc': {'subdocs.' + str(index) + '.n': 1}})
来源:https://stackoverflow.com/questions/13894769/pymongo-syntax-to-update-a-subdocument