-1

Is there a way to modify the id of all documents in a Mongo collection with spring mongo?

Trying this in many ways I got error messages like:

the (immutable) field '_id' was found to have been altered to _id

or

Write errors: [BulkWriteError{index=0, code=16837, message='The _id field cannot be changed from {_id: "xyz"} to {_id: "zxy"}.

Is there a way to do this?

neptune
  • 1,211
  • 2
  • 19
  • 32

1 Answers1

1

No, you are not allowed to update the _id field. But you can always set a brand new _id to an existing doc and remove the older _id.

sharath
  • 3,501
  • 9
  • 47
  • 72
  • when I tried to use BasicDBObject's replaceOne method to replace the id, it gives me the second error. Or it's not what you meant by set a new _id and remove the older? – neptune Jul 04 '17 at 12:53
  • I dont have access to the mongo driver now, but this is what I was hinting at (not tested) : BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("_id", 1234)); someCollection.update(someSearchQuery, set); Meanwhile, get the older _id before this and remove it after you set the new one. – sharath Jul 04 '17 at 13:02
  • check this : https://stackoverflow.com/questions/23130161/how-to-update-the-id-field-in-a-mongodb-document – sharath Jul 04 '17 at 13:02