Home > database >  Are custom _id fields in MongoDB still of type ObjectId
Are custom _id fields in MongoDB still of type ObjectId

Time:04-18

I'm building a project with MongoDB, but I'm a little bit confused on how the _id field works. My understanding is that, by default, MongoDB will generate an object of type ObjectId and assign it as the id.

However, in my server, I'm assigning an arbitrary string as the _id of an object. What I haven't quite understood yet: Is this string somehow converted to an ObjectId, or does the type of the _id field change to string?

CodePudding user response:

MongoDB will generate an _id field with an ObjectId value if an _id field does not exist in the document. If you create the _id by your own, then you can use whatever datatype you like to use. MongoDB does not modify it.

The only constraint is, it must be a unique value.

  • Related