Download as pdf or txt
Download as pdf or txt
You are on page 1of 62

Presentation by Uplatz

Contact Us: https://training.uplatz.com/


Email: info@uplatz.com
Phone:+44 7836 212635
Table of Contents

 Part 6: Query and Projection Operator


 Update documents
 Filed Update Operator
 Array Update Operator
 Field Update Operators:
Name Description
$currentDate Sets the value of a field to current
date, either as a Date or a
Timestamp.
$inc Increments the value of the field
by the specified amount.
$min Only updates the field if the
specified value is less than the
existing field value.
$max Only updates the field if the
specified value is greater than the
existing field value.
$mul Multiplies the value of the field by
the specified amount.
$rename Renames a field.
$set Sets the value of a field in a
document.
$unset Removes the specified field from
a document.
$currentDate:
 The $currentDate operator sets the value of a field to the current
date, either as a Date or a timestamp.
 The default type is Date.
 Changed in version 3.0: MongoDB no longer treats the timestamp
and the Date data types as equivalent for comparison/sorting
purposes. For details, see Date and Timestamp Comparison Order.
The $currentDate operator has the form:
{ $currentDate: { <field1>: <typeSpecification1>, ... } }
<typeSpecification> can be either:
 a boolean true to set the field value to the current date as a Date,
or
 a document { $type: "timestamp" } or { $type: "date" } which
explicitly specifies the type. The operator is case-sensitive and
accepts only the lowercase "timestamp" or the lowercase "date".
 To specify a <field> in an embedded document or in an array, use
dot notation.
Behavior:
If the field does not exist, $currentDate adds the field to a document.
Example:
Consider the following document in the users collection:
{ _id: 1, status: "a", lastModified: ISODate("2013-10-02T01:11:18.965Z")
}
The following operation updates the lastModified field to the current
date, the "cancellation.date" field to the current timestamp as well
as updating the status field to "D" and the "cancellation.reason" to
"user request".
db.users.update(
{ _id: 1 },
{
$currentDate: {
lastModified: true,
"cancellation.date": { $type: "timestamp" }
},
$set: {
status: "D",
"cancellation.reason": "user request"
}
}
)
The updated document would resemble:
{
"_id" : 1,
"status" : "D",
"lastModified" : ISODate("2014-09-17T23:25:56.314Z"),
"cancellation" : {
"date" : Timestamp(1410996356, 1),
"reason" : "user request"
}}
$inc:
The $inc operator increments a field by a specified value
and has the following form:
$inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
To specify a <field> in an embedded document or in an
array, use dot notation.
Behavior:
 The $inc operator accepts positive and negative values.
 If the field does not exist, $inc creates the field and sets
the field to the specified value.
 Use of the $inc operator on a field with a null value will
generate an error.
 $inc is an atomic operation within a single document.
Example:
Consider a collection products with the following document:
{
_id: 1,
sku: "abc123",
quantity: 10,
metrics: {
orders: 2,
ratings: 3.5
}
}
The following update() operation uses the $inc operator to
decrease the quantity field by 2 (i.e. increase by -2) and
increase the "metrics.orders" field by 1:
db.products.update(
{ sku: "abc123" },
{ $inc: { quantity: -2, "metrics.orders": 1 } }
)
The updated document would resemble:
{
"_id" : 1,
"sku" : "abc123",
"quantity" : 8,
"metrics" : {
"orders" : 3,
"ratings" : 3.5
}
}
$min:
 The $min updates the value of the field to a specified value
if the specified value is less than the current value of the
field.
 The $min operator can compare values of different types,
using the BSON comparison order.
{ $min: { <field1>: <value1>, ... } }
 To specify a <field> in an embedded document or in an
array, use dot notation.
Behavior:
 If the field does not exists, the $min operator sets the field
to the specified value.
 For comparisons between values of different types, such
as a number and a null, $min uses the BSON comparison
order.
Examples:
Use $min to Compare Numbers
Consider the following document in the collection scores:
{ _id: 1, highScore: 800, lowScore: 200 }
 The lowScore for the document currently has the value
200.
 The following operation uses $min to compare 200 to the
specified value 150 and updates the value of lowScore to
150 since 150 is less than 200:
db.scores.update( { _id: 1 }, { $min: { lowScore: 150 } } )
The scores collection now contains the following modified
document:
{ _id: 1, highScore: 800, lowScore: 150 }
The next operation has no effect since the current value of
the field lowScore, i.e 150, is less than 250:
db.scores.update( { _id: 1 }, { $min: { lowScore: 250 } } )
The document remains unchanged in the scores collection:
{ _id: 1, highScore: 800, lowScore: 150 }
Use $min to Compare Dates:
Consider the following document in the collection tags:
{
_id: 1,
desc: "crafts",
dateEntered: ISODate("2013-10-01T05:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16Z")
}
The following operation compares the current value of the
dateEntered field, i.e. ISODate("2013-10-01T05:00:00Z"), with
the specified date new Date("2013-09-25") to determine
whether to update the field:
db.tags.update(
{ _id: 1 },
{ $min: { dateEntered: new Date("2013-09-25") } }
)
The operation updates the dateEntered field:
{
_id: 1,
desc: "crafts",
dateEntered: ISODate("2013-09-25T00:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16Z")
}
$max:
 The $max operator updates the value of the field to a
specified value if the specified value is greater than the
current value of the field.
 The $max operator can compare values of different types,
using the BSON comparison order.
The $max operator expression has the form:
{ $max: { <field1>: <value1>, ... } }
To specify a <field> in an embedded document or in an
array, use dot notation.
Behavior:
If the field does not exists, the $max operator sets the field to
the specified value.
Examples:
Use $max to Compare Numbers
Consider the following document in the collection scores:

{ _id: 1, highScore: 800, lowScore: 200 }


 The highScore for the document currently has the value
800.
 The following operation uses $max to compare the 800
and the specified value 950 and updates the value of
highScore to 950 since 950 is greater than 800:

db.scores.update( { _id: 1 }, { $max: { highScore: 950 } } )

The scores collection now contains the following modified


document:
{ _id: 1, highScore: 950, lowScore: 200 }

The next operation has no effect since the current value of


the field highScore, i.e. 950, is greater than 870:
db.scores.update( { _id: 1 }, { $max: { highScore: 870 } } )

The document remains unchanged in the scores collection:


{ _id: 1, highScore: 950, lowScore: 200 }
Use $max to Compare Dates:
Consider the following document in the collection tags:
{
_id: 1,
desc: "crafts",
dateEntered: ISODate("2013-10-01T05:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16.163Z")
}
The following operation compares the current value of the
dateExpired field, i.e. ISODate("2013-10-01T16:38:16.163Z"),
with the specified date new Date("2013-09-30") to
determine whether to update the field:

db.tags.update(
{ _id: 1 },
{ $max: { dateExpired: new Date("2013-09-30") } }
)
The operation does not update the dateExpired field:

{
_id: 1,
desc: "decorative arts",
dateEntered: ISODate("2013-10-01T05:00:00Z"),
dateExpired: ISODate("2013-10-01T16:38:16.163Z")
}
$mul:
Multiply the value of a field by a number. To specify a $mul
expression, use the following prototype:
{ $mul: { <field1>: <number1>, ... } }
The field to update must contain a numeric value.
To specify a <field> in an embedded document or in an array,
use dot notation.
Behavior
Missing Field
If the field does not exist in a document, $mul creates the
field and sets the value to zero of the same numeric type as
the multiplier.
Atomic
$mul is an atomic operation within a single document.
Examples:
Multiply the Value of a Field
Consider a collection products with the following
document:
{ "_id" : 1, "item" : "ABC", "price" : NumberDecimal("10.99"),
"qty" : 25 }
The following db.collection.update() operation updates the
document, using the $mul operator to multiply the price by
1.25 and the qty field by 2:
db.products.update(
{ _id: 1 },
{ $mul: { price: NumberDecimal("1.25"), qty: 2 } } )
The operation results in the following document, where the
new value of price reflects the original value 10.99 multiplied
by 1.25 and the new value of qty reflects the original value of
25 multipled by 2:
{ "_id" : 1, "item" : "ABC", "price" : NumberDecimal("13.7375"),
"qty" : 50 }
Apply $mul Operator to a Non-existing Field:
Consider a collection products with the following document:
{ _id: 2, item: "Unknown" }
The following db.collection.update() operation updates the
document, applying the $mul operator to the field price that
does not exist in the document
db.products.update(
{ _id: 2 },
{ $mul: { price: NumberLong(100) } }
)
The operation results in the following document with a price
field set to value 0 of numeric type NumberLong, the same
type as the multiplier:
{ "_id" : 2, "item" : "Unknown", "price" : NumberLong(0) }
Multiply Mixed Numeric Types
Consider a collection products with the following document:
{ _id: 3, item: "XYZ", price: NumberLong(10) }
The following db.collection.update() operation uses the $mul
operator to multiply the value in the price field
NumberLong(10) by NumberInt(5):
db.products.update(
{ _id: 3 },
{ $mul: { price: NumberInt(5) } }
)
The operation results in the following document:
{ "_id" : 3, "item" : "XYZ", "price" : NumberLong(50) }
$rename:
The $rename operator updates the name of a field and has
the following form:
{$rename: { <field1>: <newName1>, <field2>: <newName2>,
... } }
The new field name must differ from the existing field name.
To specify a <field> in an embedded document, use dot
notation.
Consider the following example:
db.students.update( { _id: 1 }, { $rename: { 'nickname':
'alias', 'cell': 'mobile' } } )
This operation renames the field nickname to alias, and the
field cell to mobile.
Behavior
 The $rename operator logically performs an $unset of
both the old name and the new name, and then
performs a $set operation with the new name.
 As such, the operation may not preserve the order of
the fields in the document; i.e. the renamed field may
move within the document.
 If the document already has a field with the
<newName>, the $rename operator removes that field
and renames the specified <field> to <newName>.
 If the field to rename does not exist in a document,
$rename does nothing (i.e. no operation).
 For fields in embedded documents, the $rename
operator can rename these fields as well as move the
fields in and out of embedded documents.
 $rename does not work if these fields are in array
elements.
Examples
A collection students contains the following documents
where a field name appears misspelled, i.e. should be
name:
{
"_id": 1,
"alias": [ "The American Cincinnatus", "The American
Fabius" ],
"mobile": "555-555-5555",
"nmae": { "first" : "george", "last" : "washington" }
}
{
"_id": 2,
"alias": [ "My dearest friend" ],
"mobile": "222-222-2222",
"nmae": { "first" : "abigail", "last" : "adams" }
}
{
"_id": 3,
"alias": [ "Amazing grace" ],
"mobile": "111-111-1111",
"nmae": { "first" : "grace", "last" : "hopper" }
}
The examples in this section successively updates the
documents in the collection.
Rename a Field
To rename a field, call the $rename operator with the
current name of the field and the new name:
db.students.updateMany( {}, { $rename: { "nmae": "name" } }
)
This operation renames the field nmae to name for all
documents in the collection:
{
"_id": 1,
"alias": [ "The American Cincinnatus", "The American
Fabius" ],
"mobile": "555-555-5555",
"name": { "first" : "george", "last" : "washington" }
}{ "_id" : 2,
"alias" : [ "My dearest friend" ],
"mobile" : "222-222-2222",
"name" : { "first" : "abigail", "last" : "adams" } } }
{ "_id" : 3,
"alias" : [ "Amazing grace" ],
"mobile" : "111-111-1111",
"name" : { "first" : "grace", "last" : "hopper" } }
Rename a Field in an Embedded Document
 To rename a field in an embedded document, call the
$rename operator using the dot notation to refer to the
field.
 If the field is to remain in the same embedded document,
also use the dot notation in the new name, as in the
following:
db.students.update( { _id: 1 }, { $rename: { "name.first":
"name.fname" } } )
This operation renames the embedded field first to fname:
{
"_id" : 1,
"alias" : [ "The American Cincinnatus", "The American Fabius"
],
"mobile" : "555-555-5555",
"name" : { "fname" : "george", "last" : "washington" }
}
Rename a Field That Does Not Exist
When renaming a field and the existing field name refers to a
field that does not exist, the $rename operator does nothing,
as in the following:
db.students.update( { _id: 1 }, { $rename: { 'wife': 'spouse' } } )
This operation does nothing because there is no field named
wife.
$set:
 The $set operator replaces the value of a field with the
specified value.
 The $set operator expression has the following form:
{ $set: { <field1>: <value1>, ... } }
To specify a <field> in an embedded document or in an
array, use dot notation.
Behavior
 If the field does not exist, $set will add a new field with
the specified value, provided that the new field does
not violate a type constraint.
 If you specify a dotted path for a non-existent field, $set
will create the embedded documents as needed to
fulfill the dotted path to the field.
 If you specify multiple field-value pairs, $set will update
or create each field.
Examples
Consider a collection products with the following document:
{
_id: 100,
sku: "abc123",
quantity: 250,
instock: true,
reorder: false,
details: { model: "14Q2", make: "xyz" },
tags: [ "apparel", "clothing" ],
ratings: [ { by: "ijk", rating: 4 } ]
}
Set Top-Level Fields
For the document matching the criteria _id equal to 100, the
following operation uses the $set operator to update the
value of the quantity field, details field, and the tags field.
db.products.update(
{ _id: 100 },
{ $set:
{
quantity: 500,
details: { model: "14Q3", make: "xyz" },
tags: [ "coats", "outerwear", "clothing" ]
}})
The operation replaces the value of: quantity to 500; the
details field to a new embedded document, and the tags
field to a new array.
Set Fields in Embedded Documents
To specify a <field> in an embedded document or in an
array, use dot notation.
For the document matching the criteria _id equal to 100,
the following operation updates the make field in the
details document:
db.products.update(
{ _id: 100 },
{ $set: { "details.make": "zzz" } }
)
Set Elements in Arrays
To specify a <field> in an embedded document or in an
array, use dot notation.
For the document matching the criteria _id equal to 100,
the following operation updates the value second element
(array index of 1) in the tags field and the rating field in the
first element (array index of 0) of the ratings array.
db.products.update(
{ _id: 100 },
{ $set:
{
"tags.1": "rain gear",
"ratings.0.rating": 2
}})
$setOnInsert:
 If an update operation with upsert: true results in an insert
of a document, then $setOnInsert assigns the specified
values to the fields in the document.
 If the update operation does not result in an insert,
$setOnInsert does nothing.
You can specify the upsert option for either the
db.collection.update() or db.collection.findAndModify()
methods.
db.collection.update(
<query>,
{ $setOnInsert: { <field1>: <value1>, ... } },
{ upsert: true }
)
To specify a <field> in an embedded document or in an
array, use dot notation.
Example:
A collection named products contains no documents.
Then, the following db.collection.update() with upsert: true
inserts a new document.
db.products.update(
{ _id: 1 },
{
$set: { item: "apple" },
$setOnInsert: { defaultQty: 100 }
},
{ upsert: true }
)
MongoDB creates a new document with _id equal to 1 from the
<query> condition, and then applies the $set and $setOnInsert
operations to this document.
The products collection contains the newly-inserted document:
{ "_id" : 1, "item" : "apple", "defaultQty" : 100 }

If the db.collection.update() with upsert: true had found a


matching document, then MongoDB performs an update,
applying the $set operation but ignoring the $setOnInsert
operation.
$unset:
The $unset operator deletes a particular field. Consider the
following syntax:
{ $unset: { <field1>: "", ... } }
 The specified value in the $unset expression (i.e. "") does
not impact the operation.
 To specify a <field> in an embedded document or in an
array, use dot notation.
Behavior
 If the field does not exist, then $unset does nothing (i.e. no
operation).
 When used with $ to match an array element, $unset
replaces the matching element with null rather than
removing the matching element from the array.
 This behavior keeps consistent the array size and element
positions.
Example:
The following update() operation uses the $unset operator
to remove the fields quantity and instock from the first
document in the products collection where the field sku has
a value of unknown.
db.products.update(
{ sku: "unknown" },
{ $unset: { quantity: "", instock: "" } }
)
Array Update Operators:
$:
The positional $ operator identifies an element in an array to
update without explicitly specifying the position of the
element in the array.
The positional $ operator has the form:
{ "<array>.$" : value }
When used with update operations, e.g.
db.collection.update() and db.collection.findAndModify(),
 the positional $ operator acts as a placeholder for the first
element that matches the query document, and
 the array field must appear as part of the query
document.
For example:
db.collection.update(
{ <array>: value ... },
{ <update operator>: { "<array>.$" : value } }
)
Behavior:
upsert
Do not use the positional operator $ with upsert operations
because inserts will use the $ as a field name in the inserted
document.
Nested Arrays
The positional $ operator cannot be used for queries
which traverse more than one array, such as queries that
traverse arrays nested within other arrays, because the
replacement for the $ placeholder is a single value
Unsets:
When used with the $unset operator, the positional $
operator does not remove the matching element from the
array but rather sets it to null.
Examples
Update Values in an Array
Create a collection students with the following
documents:
db.students.insert([
{ "_id" : 1, "grades" : [ 85, 80, 80 ] },
{ "_id" : 2, "grades" : [ 88, 90, 92 ] },
{ "_id" : 3, "grades" : [ 85, 100, 90 ] } ])
Examples
Update Values in an Array
Create a collection students with the following documents:
db.students.insert([
{ "_id" : 1, "grades" : [ 85, 80, 80 ] },
{ "_id" : 2, "grades" : [ 88, 90, 92 ] },
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
])
To update the first element whose value is 80 to 82 in the in
the grades array, use the positional $ operator if you do not
know the position of the element in the array:
Important:
You must include the array field as part of the query
document.
db.students.updateOne(
{ _id: 1, grades: 80 }, { $set: { "grades.$" : 82 } })
db.students.updateOne(
{ _id: 1, grades: 80 },
{ $set: { "grades.$" : 82 } }
)
 The positional $ operator acts as a placeholder for the first
match of the update query document.
 After the operation, the students collection contains the
following documents:
{ "_id" : 1, "grades" : [ 85, 82, 80 ] }
{ "_id" : 2, "grades" : [ 88, 90, 92 ] }
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }
Update Documents in an Array
The positional $ operator facilitates updates to arrays that
contain embedded documents. Use the positional $
operator to access the fields in the embedded documents
with the dot notation on the $ operator.
db.collection.update(
{ <query selector> },
{ <update operator>: { "array.$.field" : value } }
)
Consider the following document in the students collection
whose grades element value is an array of embedded
documents:
{ _id: 4, grades: [ { grade: 80, mean: 75, std: 8 }, { grade: 85,
mean: 90, std: 5 }, { grade: 85, mean: 85, std: 8 } ] }
Use the positional $ operator to update the std field of the
first array element that matches the grade equal to 85
condition:
Use the positional $ operator to update the std field of the
first array element that matches the grade equal to 85
condition:
Important
You must include the array field as part of the query
document.
db.students.updateOne(
{ _id: 4, "grades.grade": 85 },
{ $set: { "grades.$.std" : 6 } }
)
Important:
You must include the array field as part of the query
document.
db.students.updateOne(
{ _id: 4, "grades.grade": 85 },
{ $set: { "grades.$.std" : 6 } }
)
After the operation, the document has the following
updated values:
{
"_id" : 4,
"grades" : [
{ "grade" : 80, "mean" : 75, "std" : 8 },
{ "grade" : 85, "mean" : 90, "std" : 6 },
{ "grade" : 85, "mean" : 85, "std" : 8 }
]}
Update Embedded Documents Using Multiple Field Matches
The $ operator can update the first array element that
matches multiple query criteria specified with the
$elemMatch() operator.
Consider the following document in the students collection
whose grades field value is an array of embedded
documents:
{
_id: 5,
grades: [
{ grade: 80, mean: 75, std: 8 },
{ grade: 85, mean: 90, std: 5 },
{ grade: 90, mean: 85, std: 3 }
]
}
In the example below, the $ operator updates the value of the
std field in the first embedded document that has grade field
with a value less than or equal to 90 and a mean field with a
value greater than 80:
db.students.updateOne(
{
_id: 5,
grades: { $elemMatch: { grade: { $lte: 90 }, mean: { $gt: 80 } }
},
{ $set: { "grades.$.std" : 6 } }
)
This operation updates the first embedded document
that matches the criteria, namely the second embedded
document in the array:
{
_id: 5,
grades: [
{ grade: 80, mean: 75, std: 8 },
{ grade: 85, mean: 90, std: 6 },
{ grade: 90, mean: 85, std: 3 }
]
}
$addToSet:
The $addToSet operator adds a value to an array unless the
value is already present, in which case $addToSet does
nothing to that array.
The $addToSet operator has the form:
{ $addToSet: { <field1>: <value1>, ... } }
To specify a <field> in an embedded document or in an
array, use dot notation.
Behavior
 $addToSet only ensures that there are no duplicate items
added to the set and does not affect existing duplicate
elements.
 $addToSet does not guarantee a particular ordering of
elements in the modified set.
Missing Field
If you use $addToSet on a field is absent in the document to
update, $addToSet creates the array field with the
Field is Not an Array
 If you use $addToSet on a field that is not an array, the
operation will fail.
 For example, consider a document in a collection foo
that contains a non-array field colors.
{ _id: 1, colors: "blue,green,red" }
The following $addToSet operation on the non-array field
colors fails:
db.foo.update(
{ _id: 1 },
{ $addToSet: { colors: "c" } }
)
Value to Add is An Array
If the value is an array, $addToSet appends the whole
array as a single element.
Consider a document in a collection test containing an
array field letters:
{ _id: 1, letters: ["a", "b"] }
The following operation appends the array [ "c", "d" ] to
the letters field:
db.test.update(
{ _id: 1 },
{ $addToSet: { letters: [ "c", "d" ] } }
)
The letters array now includes the [ "c", "d" ] array as an
element:
{ _id: 1, letters: [ "a", "b", [ "c", "d" ] ] }
Examples
Consider a collection inventory with the following document:
{ _id: 1, item: "polarizing_filter", tags: [ "electronics", "camera"
]}
Add to Array
The following operation adds the element "accessories" to
the tags array since "accessories" does not exist in the array:
db.inventory.update(
{ _id: 1 },
{ $addToSet: { tags: "accessories" } }
)
Value Already Exists
The following $addToSet operation has no effect as "camera"
is already an element of the tags array:
db.inventory.update(
{ _id: 1 },
{ $addToSet: { tags: "camera" } }
)
$each Modifier:
You can use the $addToSet operator with the $each modifier.
The $each modifier allows the $addToSet operator to add
multiple values to the array field.
A collection inventory has the following document:
{ _id: 2, item: "cable", tags: [ "electronics", "supplies" ] }
Then the following operation uses the $addToSet operator
with the $each modifier to add multiple elements to the tags
array:db.inventory.update(
{ _id: 2 },
{ $addToSet: { tags: { $each: [ "camera", "electronics",
"accessories" ] } } }
 The operation adds only "camera" and "accessories" to
the tags array since "electronics" already exists in the
array:
{
_id: 2,
item: "cable",
tags: [ "electronics", "supplies", "camera", "accessories" ]
}
$pop:
The $pop operator removes the first or last element of an
array. Pass $pop a value of -1 to remove the first element of
an array and 1 to remove the last element in an array.
The $pop operator has the form:
{ $pop: { <field>: <-1 | 1>, ... } }
To specify a <field> in an embedded document or in an
array, use dot notation.
Behavior:
 The $pop operation fails if the <field> is not an array.
 If the $pop operator removes the last item in the <field>,
the <field> will then hold an empty array.
Examples:
Remove the First Item of an Array
Given the following document in a collection students:
{ _id: 1, scores: [ 8, 9, 10 ] }
The following example removes the first element (8) in the
scores array:
db.students.update( { _id: 1 }, { $pop: { scores: -1 } } )
After the operation, the updated document has the first
item 8 removed from its scores array:
{ _id: 1, scores: [ 9, 10 ] }
Remove the Last Item of an Array:
Given the following document in a collection students:
{ _id: 1, scores: [ 9, 10 ] }
The following example removes the last element (10) in the
scores array by specifying 1 in the $pop expression:
db.students.update( { _id: 1 }, { $pop: { scores: 1 } } )
After the operation, the updated document has the last
item 10 removed from its scores array:
{ _id: 1, scores: [ 9 ] }
$pull:
The $pull operator removes from an existing array all
instances of a value or values that match a specified
condition.
The $pull operator has the form:
{ $pull: { <field1>: <value|condition>, <field2>:
<value|condition>, ... } }
To specify a <field> in an embedded document or in an
array, use dot notation.
Examples
Remove All Items That Equal a Specified Value
Given the following document in the stores collection:
{
_id: 1,
fruits: [ "apples", "pears", "oranges", "grapes", "bananas"
],
vegetables: [ "carrots", "celery", "squash", "carrots" ]
}
{
_id: 2,
fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]
}
The following operation updates all documents in the
collection to remove "apples" and "oranges" from the array
fruits and remove "carrots" from the array vegetables:
db.stores.update(
{ },
{ $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables:
"carrots" } },
{ multi: true }
)
After the operation, the fruits array no longer contains any
"apples" or "oranges" values, and the vegetables array no
longer contains any "carrots" values:
{
"_id" : 1,
"fruits" : [ "pears", "grapes", "bananas" ],
"vegetables" : [ "celery", "squash" ]
}
{ "_id" : 2, "fruits" : [ "plums", "kiwis", "bananas" ], "vegetables" :
[ "broccoli", "zucchini", "onions" ] }
Remove All Items That Match a Specified $pull Condition
Given the following document in the profiles collection:
{ _id: 1, votes: [ 3, 5, 6, 7, 7, 8 ] }
The following operation will remove all items from the votes
array that are greater than or equal to ($gte) 6:
db.profiles.update( { _id: 1 }, { $pull: { votes: { $gte: 6 } } } )
After the update operation, the document only has values
less than 6:
{ _id: 1, votes: [ 3, 5 ] }
Remove Items from an Array of Documents
A survey collection contains the following documents:
{_id: 1,
results: [
{ item: "A", score: 5 },
{ item: "B", score: 8, comment: "Strongly agree" }
]
}{
_id: 2,
results: [
{ item: "C", score: 8, comment: "Strongly agree" },
{ item: "B", score: 4 }
]
}
The following operation will remove from the results array all
elements that contain both a score field equal to 8 and an
item field equal to "B":
db.survey.update(
{ },
{ $pull: { results: { score: 8 , item: "B" } } },
{ multi: true }
)
 The $pull expression applies the condition to each
element of the results array as though it were a top-level
document.
 After the operation, the results array contains no
documents that contain both a score field equal to 8
and an item field equal to "B".
{
"_id" : 1,
"results" : [ { "item" : "A", "score" : 5 } ]
}
{
"_id" : 2,
"results" : [
{ "item" : "C", "score" : 8, "comment" : "Strongly agree" },
{ "item" : "B", "score" : 4 }
]}
Because $pull operator applies its query to each element
as though it were a top-level object, the expression did not
require the use of $elemMatch to specify the condition of
a score field equal to 8 and item field equal to "B". In fact,
the following operation will not pull any element from the
original collection.
db.survey.update(
{ },
{ $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } },
{ multi: true } }
 However, if the survey collection contained the
following documents, where the results array contains
embedded documents that also contain arrays:
{ _id: 1,
results: [
{ item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ]
},
{ item: "B", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 9 } ]
}] }
{
_id: 2,
results: [
{ item: "C", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 7 } ]
},
{ item: "B", score: 4, answers: [ { q: 1, a: 0 }, { q: 2, a: 8 } ]
}
]}
Then you can specify multiple conditions on the elements of
the answers array with $elemMatch:
db.survey.update(
{ },
{ $pull: { results: { answers: { $elemMatch: { q: 2, a: { $gte: 8 } }
} } } },
{ multi: true } )
The operation removed from the results array those
embedded documents with an answers field that contained
at least one element with q equal to 2 and a greater than or
equal to 8:
{
"_id" : 1,
"results" : [
{ "item" : "A", "score" : 5, "answers" : [ { "q" : 1, "a" : 4 }, { "q"
: 2, "a" : 6 } ] ] }
.
Update Operator

Field Update
Summary: Operator

Array
Update
Operator
Thank You………
If you have any quries please write to info@uplatz.com".

You might also like