Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Sounds like you want to use the $elemMatch operator in conjunction with the '$' positional operator:</p> <p><a href="http://docs.mongodb.org/manual/reference/operator/elemMatch/" rel="nofollow">http://docs.mongodb.org/manual/reference/operator/elemMatch/</a> <a href="http://docs.mongodb.org/manual/reference/operator/positional/" rel="nofollow">http://docs.mongodb.org/manual/reference/operator/positional/</a></p> <p>Let's take your example. Let's say you want to find the element in the user's "ownedItems" list where the "company_id" is 3, and update that element's "item_amount" by 5. That can be done in a single update statement like so: </p> <pre><code>Users.update( { userId: _id, ownedItems : { $elemMatch : { company_id : 3 } } }, { $inc : { ownedItems.$.item_amount : 5 } } ) </code></pre> <p>The <strong>$elemMatch</strong> operator makes it explicit which of the elements of the list you're querying for. You can then use the <strong>$</strong> operator in the modifier clause to refer to that matched element and make changes to it.</p> <p>If the "ownedItems" list of the user does not have any entry matching { "company_id" : 3 } then the above update will not do anything. If that happens, you can do a second update with the <strong>$addToSet</strong> operator to add a new entry like so:</p> <pre><code>Users.update( { userId: _id }, { $addToSet : { ownedItems : { company_id : 3, item_amount : 5 } } } ) </code></pre> <p><a href="http://docs.mongodb.org/manual/reference/operator/addToSet/" rel="nofollow">http://docs.mongodb.org/manual/reference/operator/addToSet/</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload