Alter/Convert ObjectId to the string value in MongoDB

Jak
Jak
Member
388 Points
159 Posts

I'm getting issue with fetching records from collection with objectId as:

{ "_id" : ObjectId("5c92b80036de59bd9de0639d"), "UserName" : "John" }
{ "_id" : ObjectId("5c92b80436de59bd9de0639e"), "UserName" : "Chris" }
{ "_id" : ObjectId("5c92b80936de59bd9de0639f"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c92b81836de59bd9de063a0"), "UserName" : "Robert" }

And getting error as:

System.FormatException: 'An error occurred while deserializing the _id property of class CollectionBase: Cannot deserialize a 'String' from BsonType 'ObjectId'.'

Due to common uses of code logic, can't change it. Is there any way to modify/convert object id to the string in mongodb collection itself?

Convert to Something like:

{ "_id" : "5c92b80036de59bd9de0639d", "UserName" : "John" }
{ "_id" : "5c92b80436de59bd9de0639e", "UserName" : "Chris" }
{ "_id" : "5c92b80936de59bd9de0639f", "UserName" : "Larry" }
{ "_id" : "5c92b81836de59bd9de063a0", "UserName" : "Robert" }
Views: 148
Total Answered: 1
Total Marked As Answer: 1
Posted On: 30-Jun-2020 23:25

Share:   fb twitter linkedin
Answers
Brian
Brian
Participant
612 Points
81 Posts
         

The _id value of a document is immutable, so we can create a new copy of the document with the string type _id value from objectId type, and then delete the original document.

Following will be the command look like:

db.getCollection('dbCollectionName').find({_id:{ $type: "objectId" }}).forEach( function (x) {
  var oldId = x._id;
  x._id = x._id.valueOf(); // convert field to string
  db.getCollection('dbCollectionName').insert(x);
  db.getCollection('dbCollectionName').remove({_id: oldId});
});

OR

db.dbCollectionName.find({_id:{ $type: "objectId" }}).forEach( function (x) {
  var oldId = x._id;
  x._id = x._id.valueOf(); // convert field to string
  db.dbCollectionName.insert(x);
  db.dbCollectionName.remove({_id: oldId});
});
Posted On: 01-Jul-2020 02:10
Thanks.
 - Jak  02-Jul-2020 01:01
 Log In to Chat