Database Reference
In-Depth Information
The following example uses regex in a query to find all items in the media collection that start with the word “Matrix:”
> db.media.find ( { Title : /Matrix*/i } )
Using regular expressions from MongoDB can make your life much simpler, so we'd recommend exploring this
feature in greater detail as time permits or your circumstances can benefit from it.
Updating Data
So far you've learned how to insert and query for data in your database. Next, you'll learn how to update that data.
MongoDB supports quite a few update operators that you'll learn how to use in the following sections.
Updating with update()
MongoDB comes with the
update()
function for performing updates to your data. The
update()
function takes three
primary arguments:
criteria
,
objNew
and
options
.
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} )
■
Note
an
upsert
tells the database to “update a record if a document is present or to insert the record if it isn't.”
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.