Marcus Riemer
Marcus Riemer

Reputation: 7698

Update a single list item of a Mongo DB document

I have the following document structure inside a mongodb collection:

{ _id: XXX, Name: "Example", References: [ { RefId: YYY, RefCount: 2 }, ...] }

What puzzles me, is how to write a update() operation that increments exactly one of the reference Ids (RefId) by one. The document that needs an update to its references will be identified by its _id field.

I know about the possibility to replace the entire document, but if possible I would like to avoid that.

Upvotes: 2

Views: 1304

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312055

Use the $ positional operator in your update to identify the element in the array that your query parameter matched.

So something like:

t.update({_id: XXX, 'References.RefId': YYY}, {$inc: {'References.$.RefCount': 1}});

Upvotes: 3

Related Questions