Database Reference
In-Depth Information
sale: 1299,
}
}
]
}
You want to be able to set the quantity of the second line item, with the SKU of 10027,
to 5. The problem is that you don't know where in the line_items array this particu-
lar sub-document resides. You don't even know whether it exists. But a simple query
selector, and an update document using the positional operator, solve both of these
problems:
query = {_id: ObjectId("4c4b1476238d3b4dd5003981"),
'line_items.sku': "10027"}
update = {$set: {'line_items.$.quantity': 5}}
db.orders.update(query, update)
The positional operator is the $ that you see in the 'line_items.$.quantity' string.
If the query selector matches, then the index of the document having a SKU of 10027
will replace the positional operator internally, thereby updating the correct document.
If your data model includes sub-documents, then you'll find the positional opera-
tor very useful for performing nuanced document updates.
6.4.3
The findAndModify command
With so many fleshed-out examples of using the findAndModify command earlier in
this chapter, it only remains to enumerate its options. Of the following, the only
options required are query and either update or remove :
query —A document query selector. Defaults to {} .
update —A document specifying an update. Defaults to {} .
remove —A Boolean value that, when true , removes the object and then returns
it. Defaults to false .
new —A Boolean that, if true , returns the modified document as it appears after
the update has been applied. Defaults to false .
sort —A document specifying a sort direction. Because findAndModify will
modify only one document at a time, the sort option can be used to help con-
trol which matching document is processed. For example, you might sort by
{created_at: -1} to process to most recently created matching document.
fields —If you only need to return a subset of fields, use this option to specify
them. This is especially helpful with larger documents. The fields are specified
just as they would be in any query. See the section on fields in chapter 5 for
examples.
upsert —A Boolean that, when true , treats findAndModify as an upsert. If the
document sought doesn't exist, it'll be created. Note that if you want to return
the newly created document, you also need to specify {new: true} .
Search WWH ::




Custom Search