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?
You can update a record, or document as it is called in MongoDB, by using the update_one() method. The first parameter of the update_one() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated.
Updating all Documents in a Collection. PyMongo includes an update_many() function which updates all the documents which satisfy the given query. filter – It is the first parameter which is a criteria according to which the documents that satisfy the query are updated.
To update a single field or specific fields just use the $set operator. This will update a specific field of "citiName" by value "Jakarta Pusat" that defined by $set operator.
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}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With