How do I pass an ordinal position into the update document in Pymongo for an $inc update

mongodb, pymongo

Solution

You need to generate your key programmatically:

In the shell:

var num = 4;
var inc = {};
inc['nested.' + num + '.c'] = 1;
db.collection.update({_id: 'adsjfdsau7Hukad'}, {$inc: inc})

In pymongo:

num = 4
db.collection.update(
    {'_id': 'adsjfdsau7Hukad'},
    {'$inc': {'nested.' + str(num) + '.c': 1}})

Problem

I have a document with a nested array of documents that do not have ids ``` _id: adsjfdsau7Hukad, 'nested':[{ a:'123456',b:'zzzzzzzzz'}, {a:'788123',b:'6yuuuuuu'}, {a:'123456',b:'ooo998uj'}] ``` I want to increment a new property, 'c' in a specified element of an identified document. For instance: ``` db.collection.update({_id:'adsjfdsau7Hukad'},{$inc:{'nested.2.c':1}}) ``` This works when I can explicitly write the element ordinal position identifier. But, I need to pass a variable for the element ordinal position, and I have not found a way to do so. I tried this: ``` var num = 4 ## as example db.collection.update({_id:'adsjfdsau7Hukad','nested.$': num},{$inc:{'nested.$.c':1}}) ``` but this does not seem to work. Any ideas?

Original source