On this page本页内容
$rename
¶The $rename
operator updates the name of a field and has the following form:$rename
运算符更新字段的名称,其形式如下:
The new field name must differ from the existing field name. 新字段名必须与现有字段名不同。To specify a 要在嵌入式文档中指定<field>
in an embedded document, use dot notation.<field>
,请使用点表示法。
Consider the following example:考虑下面的例子:
This operation renames the field 此操作将字段nickname
to alias
, and the field cell
to mobile
.nickname
重命名为alias
,将字段cell
重命名为mobile
。
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. $rename
运算符在逻辑上对旧名称和新名称执行$unset
,然后对新名称执行$set
操作。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>
.<newName>
的字段,$rename
运算符将删除该字段,并将指定的<field>
重命名为<newName>
。
If the field to rename does not exist in a document, 如果要重命名的字段在文档中不存在,$rename
does nothing (i.e. no operation).$rename
不执行任何操作(即不执行任何操作)。
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
运算符可以重命名这些字段,并将字段移入和移出嵌入文档。如果这些字段位于数组元素中,$rename
does not work if these fields are in array elements.$rename
不起作用。
A collection students
contains the following documents where a field nmae
appears misspelled, i.e. should be name
:students
集合包含以下文档,其中字段nmae
出现拼写错误,即应为name
:
The examples in this section successively updates the documents in the collection.本节中的示例依次更新了集合中的文档。
To rename a field, call the 要重命名字段,请使用字段的当前名称和新名称调用$rename
operator with the current name of the field and the new name:$rename
运算符:
This operation renames the field 此操作将集合中所有文档的字段nmae
to name
for all documents in the collection:nmae
重命名为name
:
To rename a field in an embedded document, call the 要重命名嵌入文档中的字段,请使用点符号调用$rename
operator using the dot notation to refer to the field. $rename
运算符来引用该字段。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
:first
重命名为fname
:
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:$rename
运算符不执行任何操作,如下所示:
This operation does nothing because there is no field named 此操作不执行任何操作,因为没有名为wife
.wife
的字段。
See also参阅