zelinka
zelinka

Reputation: 3413

inserting into a mongodb collection with manually specified _id

Suppose I have a collection in mongodb and the objects in the collection have an _id that is an ObjectID that I selected in some random manner completely external to mongoDB, such as starting with ObjectID 0000 ... 0000 and incrementing by 10000, or maybe just used a random number generator to make the ObjectID's.

Suppose I then go to add another item to the collection, but I don't have an ObjectID in mind for the new object, and am satisfied with letting the system pick one. Would the system ever select a ObjectID that was already a part of the collection?

If it is relevant, I am using the java API and the python API to do this.

Upvotes: 0

Views: 544

Answers (1)

SiddAjmera
SiddAjmera

Reputation: 39432

_id is always unique. There's an implicit unique primary index on _id field.

So rest assured that MongoDB will not choose an _id field that has been taken.

Also the _id field is a 12 byte hexadecimal string in which :

  • 4 bytes is for the date timestamp.
  • 3 bytes is the MAC Address.
  • 2 bytes is the process id.
  • 3 bytes is the counter.

So if MongoDB chooses an _id for your document in a collection, it's definitely going to be unique from the other _id fields in other documents in your collection.

Hope this helps.

Upvotes: 0

Related Questions