Oamar Kanji
Oamar Kanji

Reputation: 2224

How to convert all _id fields in a mongodb collection to ObjectId type

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?

Upvotes: 1

Views: 1144

Answers (2)

Emmanuel Okoh
Emmanuel Okoh

Reputation: 1

In other to resolve this seamlessly, it is best you structure and define your schema such that the _id type is in sync with your mongoDB _id.
If your mongoDB _id type is a string.

const mongoSchema = new mongoose.Schema({
  name: String,

  _id: String, //defining id to string type
  author: String,
  isPublished: Boolean,
  price: Number,

  tags: [String],
  date: Date,
})

If your MongoDB _id is an ObjectId, use this pattern and MongoDB will create and match the _id to the ObjectId type seamlessly.

const mongoSchema = new mongoose.Schema({
  name: String,
  author: String,
  isPublished: Boolean,
  price: Number,

  tags: [String],
  date: Date,
})

Upvotes: 0

Lord Bee
Lord Bee

Reputation: 150

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.

Upvotes: 0

Related Questions