OPTIONS

$rename

$rename

New in version 1.7.2.

Syntax: {$rename: { <old name1>: <new name1>, <old name2>: <new name2>, ... } }

The $rename operator updates the name of a field. The new field name must differ from the existing field name.

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 new field name, the $rename operator removes that field and renames the field with the old field name to the new field name.

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 the following document where a field nmae 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" }
}

The examples in this section successively updates this document.

Rename a Field

To rename a field, call the $rename operator with the current name of the field and the new name:

db.students.update( { _id: 1 }, { $rename: { "nmae": "name" } } )

This operation renames the field nmae to name:

{
  "_id": 1,
  "alias": [ "The American Cincinnatus", "The American Fabius" ],
  "mobile": "555-555-5555",
  "name": { "first" : "george", "last" : "washington" }
}

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.

←   $mul $setOnInsert  →