Database Reference
In-Depth Information
Using
$unset
with arrays
Note that using
$unset
on individual array elements may not work exactly like you
want it to. Instead of removing the element altogether, it merely sets that element's
value to
null
. To completely remove an array element, see the
$pull
and
$pop
operators.
db.readings.update({_id: 325}, {$unset: {'temp.f': 1})
db.readings.update({_id: 326}, {$unset: {'temp.0': 1})
A
RRAY
UPDATE
OPERATORS
The centrality of arrays in MongoDB's document model should be apparent. Naturally,
MongoDB provides a handful of update operators that apply exclusively to arrays.
$push and $pushAll
If you need to append values to an array,
$push
and
$pushAll
are your friends. The
first of these,
$push
, will add a single value to an array, whereas
$pushAll
supports
adding a list of values. For example, adding a new tag to the shovel product is easy
enough:
db.products.update({slug: 'shovel'}, {$push: {'tags': 'tools'}})
If you need to add a few tags in the same update, that's not a problem either:
db.products.update({slug: 'shovel'},
{$pushAll: {'tags': ['tools', 'dirt', 'garden']}})
Note you can push values of any type onto an array, not just scalars. For an example of
this, see the code in the previous section that pushed a product onto the shopping
cart's line items array.
$addToSet and $each
$addToSet
also appends a value to an array but does so in a more discerning way: the
value is added only if it doesn't already exist in the array. Thus, if your shovel has
already been tagged as a
tool
then the following update won't modify the document
at all:
db.products.update({slug: 'shovel'}, {$addToSet: {'tags': 'tools'}})
If you need to add more than one value to an array uniquely in the same operation,
then you must use
$addToSet
with the
$each
operator. Here's how that looks:
db.products.update({slug: 'shovel'},
{$addToSet: {'tags': {$each: ['tools', 'dirt', 'steel']}}})
Only those values in the
$each
that don't already exist in
tags
will be appended.
$pop
The most elementary way to remove an item from an array is with the
$pop
operator. If
$push
appends an item to an array, a subsequent
$pop
will remove that last item
pushed. Though it's frequently used with
$push
, you can use
$pop
on its own. If your