Home > Mobile >  How to convert all _id fields in a mingodb collection to ObjectId type
How to convert all _id fields in a mingodb collection to ObjectId type

Time:07-12

I have imported documents into a collection from a JSON file. I created the _id field using the node.js ObjectId function like so:

_id: ObjectId()

This creates the _id value which looks like this in the JSON document:

enter image description here

Once this is saved as JSON and loaded into mongodb, it is 'stringified' and is no longer an ObjectId type:

enter image description here

I now want to convert all _id properties in my mongoDb collection to ObjectId type.

I know that if I did not specify an _id, that mongo would have created one for me in the desired ObjectId type but this does not work for me as other collections that I have created already use this _id value that I have created.

Any idea how to convert all the documents _id to ObjectId type? What would the specific code be to do this?

CodePudding user response:

I think you could follow the idea here. change MongoDB id from string to objectId

Alternatively, since you seem to have access to the data, before importing into MongoDB, when generating your json, store the '_id' field in this format before importing.

  "_id": {
    "$oid": "621cfa31f0fc870004a35a8c"
  }

The 'oid' tells MongoDB that the type is an object id.

  • Related