Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 640
This Old Dog Avatar asked Aug 05 '13 22:08

This Old Dog


People also ask

How do you update a record in MongoDB Python?

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.

How do I update all documents in PyMongo?

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.

How do I update a single field in MongoDB?

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.


1 Answers

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}})
like image 64
JohnnyHK Avatar answered Sep 28 '22 16:09

JohnnyHK