Database Reference
In-Depth Information
Setting a Field's Value
You can use the
$set
operator to set a field's value to one you specify. This goes for any
datatype, as in the following example:
> db.media.update ( { "Title" : "Matrix, The" }, {$set : { Genre :
"Sci-Fi" } } )
This snippet would update the genre in the document created earlier, setting it to
Sci-Fi
instead.
Deleting a Specified Field
The
$unset
operator lets you delete a given field, as in this example:
> db.media.update ( {"Title": "Matrix, The"}, {$unset : { "Genre" : 1 } } )
This snippet would delete the
Genre
key and its value from the document.
Appending a Value to a Specified Field
The
$push
operator allows you to append a value to a specified field. If the field is an
existing array, then the value will be added. If the field doesn't exist yet, then the field will
be set to the array value. If the field exists, but it isn't an array, then an error condition will
be raised.
Begin by adding another author to your entry in the collection:
> db.media.update ( {"ISBN" : "978-1-4302-5821-6"}, {$push: { Author :
"Griffin,
Stewie"} } )
The next snippet raises an error message because the
Title
field is not an array:
> db.media.update ( {"ISBN" : "978-1-4302-5821-6"}, {$push: { Title :
"This isn't an array"} } )
Cannot apply $push/$pushAll modifier to non-array
The following example shows how the document looks in the meantime:
> db.media.find ( { "ISBN" : "978-1-4302-5821-6" } )
{
"Author" :
[
"Hows, David",
"Membrey, Peter",
"Plugge, Eelco",
"Griffin, Stewie",
],