Database Reference
In-Depth Information
The criteria argument lets you specify the query that selects the record you want to
update. You use the objNew argument to specify the updated information; or you can use
an operator to do this for you. The options argument lets you specify your options when
updating the document, and has two possible values: upsert and multi . The upsert
option lets you specify whether the update should be an upsert —that is, it tells MongoDB
to update the record if it exists, and create it if it doesn't. Finally, the multi option lets
you specify whether all matching documents should be updated or just the first one (the
default action).
The following simple example uses the update() function without any fancy
operators:
> db.media.update( { "Title" : "Matrix, The"}, {"Type" : "DVD", "Title" :
"Matrix, The", "Released" : 1999, "Genre" : "Action"}, { upsert: true} )
This example overwrites the document in the collection and saves it with the new
values specified. Note that any fields that you leave out are removed (the document is
basically being rewritten). Because the upsert argument is specified as true , any fields
that do not exist yet will be added (the Genre key/value pair, in this case).
In case there happen to be multiple documents matching the criteria and you wish
to upsert them all, the upsert and multi options can be added while using the $set
modifier operator as shown here:
> db.media.update( { "Title" : "Matrix, The"}, {$set: {"Type" : "DVD",
"Title" :
"Matrix, The", "Released" : 1999, "Genre" : "Action"} }, {upsert: true,
multi: true} )
an upsert tells the database to “update a record if a document is present or to
insert the record if it isn't.”
Note
Implementing an Upsert with the save( ) Command
You can also perform an upsert with the save() command. To do this, you need to specify
the _id value; you can have this value added automatically or specify it manually yourself.
If you do not specify the _id value, the save() command will assume it's an insert and
simply add the document into your collection.
The main benefit of using the save() command is that you do not need to specify
that the upsert method should be used in conjunction with the update() command.
Thus, the save() command gives you a quicker way to upsert data. In practice, the save()
and update() commands look similar:
> db.media.update( { "Title" : "Matrix, The"}, {"Type" : "DVD", "Title" :
"Matrix, The", "Released" : "1999", "Genre" : "Action"}, { upsert: true} )
 
 
Search WWH ::




Custom Search