- Reference >
- Operators >
- Update Operators >
- Array Update Operators >
- $ (query)
$ (query)¶
On this page
Definition¶
-
$¶ Syntax:
{ "<array>.$" : value }The positional
$operator identifies an element in anarrayfield to update without explicitly specifying the position of the element in the array. To project, or return, an array element from a read operation, see the$projection operator.When used with the
update()method,- the positional
$operator acts as a placeholder for the first element that matches the query document, and - the
arrayfield must appear as part of thequery document.
- the positional
Behavior¶
Upserts¶
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.
Negations¶
If the query matches the array using a negation operator, such as
$ne, $not, or $nin, then you cannot use the
positional operator to update values from this array.
However, if the negated portion of the query is inside of an
$elemMatch expression, then you can use the positional
operator to update this field.
Examples¶
Update Values in an Array¶
Consider a collection students with the following documents:
To update 80 to 82 in the grades array in the
first document, use the positional $ operator if
you do not know the position of the element in the array:
Remember that the positional $ operator acts as a
placeholder for the first match of the update query
document.
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.
Consider the following document in the students collection whose
grades field value is an array of embedded documents:
Use the positional $ operator to update the value of the
std field in the embedded document with the grade of 85: