Sarath TS
Sarath TS

Reputation: 2462

How to change data type of a field using mongo shell?

Is it possible to change the data type. eg I have a field 'user' and it's datatype is string. I need to change it's data type to ObjectId.

I have tried but getting error.

> db.booking.find().foreach( function (x) { x.user = ObjectId(x.user); db.booking.save(x); });
2017-06-28T09:30:35.317+0000 E QUERY    [thread1] TypeError: db.booking.find(...).foreach is not a function :
@(shell):1:1
>

Upvotes: 1

Views: 1966

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

The best way is to use the bulk operations API with .bulkWrite():

var ops = [];
db.booking.find({},{ "user": 1 }).forEach(doc => {
  doc.user = new ObjectId(doc.user.valueOf());

  ops.push({
    "updateOne": {
      "filter": { "_id": doc._id },
      "update": {
        "$set": { "user": doc.user }
      }
    }
  });

  if ( ops.length >= 500 ) {
    db.booking.bulkWrite(ops);
    ops = [];
  }
});

if ( ops.length > 0 ) {
  db.booking.bulkWrite(ops);
  ops = [];
}

As opposed to methods like .save() this only updates the specified field, as well as actually only committing in "batches" to the server, so you remove the overhead of back and forth communication on each write to only one write and acknowledge per batch. Using 500 is a reasonable size, but the underlying driver and server will always separate at 1000.

Upvotes: 1

Related Questions