You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child values.
If p is the object retrieved:
existing = p['d']['a']
For pymongo versions < 3.0
db.ProductData.update({
'_id': p['_id']
},{
'$set': {
'd.a': existing + 1
}
}, upsert=False, multi=False)
For pymongo versions >= 3.0
db.ProductData.update_one({
'_id': p['_id']
},{
'$set': {
'd.a': existing + 1
}
}, upsert=False)
However if you just need to increment the value, this approach could introduce issues when multiple requests could be running concurrently. Instead you should use the $inc syntax:
For pymongo versions < 3.0:
db.ProductData.update({
'_id': p['_id']
},{
'$inc': {
'd.a': 1
}
}, upsert=False, multi=False)
For pymongo versions >= 3.0:
db.ProductData.update_one({
'_id': p['_id']
},{
'$inc': {
'd.a': 1
}
}, upsert=False)
This ensures your increments will always happen.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…