- Reference >
- Operators >
- Update Operators >
- Field Update Operators >
- $rename
$rename¶
On this page
Definition¶
-
$rename
¶ The
$rename
operator updates the name of a field and has the following form: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:
This operation renames the field
nickname
toalias
, and the fieldcell
tomobile
.
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 nmae
appears misspelled, i.e. should be name
:
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:
This operation renames the field nmae
to name
for all documents
in the collection:
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:
This operation renames the embedded field first
to fname
: