Database Reference
In-Depth Information
tags
array contains the values
['tools',
'dirt',
'garden',
'steel']
, then the fol-
lowing
$pop
will remove the
steel
tag:
db.products.update({slug: 'shovel'}, {$pop: {'tags': 1}})
Like
$unset
,
$pop
's syntax is
{$pop:
{'elementToRemove':
1}}
. But unlike
$unset
,
$pop
takes a second possible value of
-1
to remove the first element of the array.
Here's how to remove the
tools
tag from the array:
db.products.update({slug: 'shovel'}, {$pop: {'tags': -1}})
One possible point of frustration is that you can't actually return the value that
$pop
removes from the array. Thus, despite its name,
$pop
doesn't work exactly like the
stack operation you probably have in mind. Be aware of this.
$pull and $pullAll
$pull
is
$pop
's more sophisticated cousin. With
$pull
, you specify exactly which array
element to remove by value, not by position. Returning to the tags example, if you
need to remove the tag
dirt
, you don't need to know where in the array it's located;
you simply tell the
$pull
operator to remove it:
db.products.update({slug: 'shovel'}, {$pull {'tags': 'dirt'}})
$pullAll
works analogously to
$pushAll
, allowing you to provide a list of values to
remove. To remove both the tags
dirt
and
garden
, you can use
$pullAll
like so:
db.products.update({slug: 'shovel'}, {$pullAll {'tags': ['dirt', 'garden']}})
P
OSITIONAL
UPDATES
It's common to model data in MongoDB using an array of sub-documents, but it
wasn't so easy to manipulate those sub-documents until the positional operator came
along. The positional operator allows you to update a sub-document in an array. You
identify which sub-document you want to update by using dot notation in your query
selector. This is hard to understand without an example, so suppose you have an order
document, part of which looks like this:
{ _id: new ObjectId("6a5b1476238d3b4dd5000048"),
line_items: [
{ _id: ObjectId("4c4b1476238d3b4dd5003981"),
sku: "9092",
name: "Extra Large Wheel Barrow",
quantity: 1,
pricing: {
retail: 5897,
sale: 4897,
}
},
{ _id: ObjectId("4c4b1476238d3b4dd5003981"),
sku: "10027",
name: "Rubberized Work Glove, Black",
quantity: 2,
pricing: {
retail: 1499,