ChatGPT解决这个技术问题 Extra ChatGPT

How can I rename a field for all documents in MongoDB?

Assuming I have a collection in MongoDB with 5000 records, each containing something similar to:

{
"occupation":"Doctor",
"name": {
   "first":"Jimmy",
   "additional":"Smith"
}

Is there an easy way to rename the field "additional" to "last" in all documents? I saw the $rename operator in the documentation but I'm not really clear on how to specify a subfield.


T
Thomas Rosen

You can use:

db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true);

Or to just update the docs which contain the property:

db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true);

The false, true in the method above are: { upsert:false, multi:true }. You need the multi:true to update all your records.

Or you can use the former way:

remap = function (x) {
  if (x.additional){
    db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});
  }
}

db.foo.find().forEach(remap);

In MongoDB 3.2 you can also use

db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )

The general syntax of this is

db.collection.updateMany(filter, update, options)

https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/


Just a word for if you are banging your head against the wall because nothing is mass updated: the false, true in the update method of the $rename version are: { upsert:false, multi:true }. You need the multi:true to update all your records.
and if I'm getting it upsert:true will create field name if field name does not exists, defaults to false.
For some reason, this didn't work for me when I used the "table.field" : "table.field" syntax. It did work when I just used the "field" : "field" syntax.
@Steve name.last is not table.field. If you read the question, you can see that the name field holds an object.
Is this working with arrays as well? Can I do: db.foo.update({}, {$rename:{"name.0.additional":"name.0.last"}}, false, true)?
X
Xavier Guihot

You can use the $rename field update operator:

db.collection.update(
  {},
  { $rename: { 'name.additional': 'name.last' } },
  { multi: true }
)

According to the new documentation, it should look like: db.collectionName.updateMany({}, { $rename : { 'name.additional' : 'name.last' } } )
@1r3k this is old but to help others avoid confusion, no, updateMany is a Mongoose command, not a MongoDB command. that command won't work.
@ChumiestBucket no, this is correct. UpdateMany is a mongodb command. See here: docs.mongodb.com/manual/reference/method/…
c
cortex

If ever you need to do the same thing with mongoid:

Model.all.rename(:old_field, :new_field)

UPDATE

There is change in the syntax in monogoid 4.0.0:

Model.all.rename(old_field: :new_field)

There is change in the syntax in the last monogoid (4.0.0) Model.all.rename(old_field: :new_field)
How can i use this option for embeded document
G
Gilad Green

Anyone could potentially use this command to rename a field from the collection (By not using any _id):

dbName.collectionName.update({}, {$rename:{"oldFieldName":"newFieldName"}}, false, true);

see FYI


d
d1jhoni1b

This nodejs code just do that , as @Felix Yan mentioned former way seems to work just fine , i had some issues with other snipets hope this helps.

This will rename column "oldColumnName" to be "newColumnName" of table "documents"

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
//var url = 'mongodb://localhost:27017/myproject';
var url = 'mongodb://myuser:mypwd@myserver.cloud.com:portNumber/databasename';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  renameDBColumn(db, function() {
    db.close();
  });

});

//
// This function should be used for renaming a field for all documents
//
var renameDBColumn = function(db, callback) {
  // Get the documents collection
  console.log("renaming database column of table documents");
  //use the former way:
  remap = function (x) {
    if (x.oldColumnName){
      db.collection('documents').update({_id:x._id}, {$set:{"newColumnName":x.oldColumnName}, $unset:{"oldColumnName":1}});
    }
  }

  db.collection('documents').find().forEach(remap);
  console.log("db table documents remap successfully!");
}

S
Swadeshi

I am using ,Mongo 3.4.0

The $rename operator updates the name of a field and has the following form:

{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }

for e.g

db.getCollection('user').update( { _id: 1 }, { $rename: { 'fname': 'FirstName', 'lname': 'LastName' } } )

The new field name must differ from the existing field name. To specify a in an embedded document, use dot notation.

This operation renames the field nmae to name for all documents in the collection:

db.getCollection('user').updateMany( {}, { $rename: { "add": "Address" } } )

db.getCollection('user').update({}, {$rename:{"name.first":"name.FirstName"}}, false, true);

In the method above false, true are: { upsert:false, multi:true }.To update all your records, You need the multi:true.

Rename a Field in an Embedded Document

db.getCollection('user').update( { _id: 1 }, { $rename: { "name.first": "name.fname" } } )

use link : https://docs.mongodb.com/manual/reference/operator/update/rename/


The embedding option is not working... I get this error "cannot use the part (address of address.city) to traverse the element"
J
Jon Kern

If you are using MongoMapper, this works:

Access.collection.update( {}, { '$rename' => { 'location' => 'location_info' } }, :multi => true )