0

If I define a model in mongoose, and create a document using something like the code below:

const Model = require("./Model")

const newModelItem = new Model({
...data
})

await newModelItem.save()

I noticed that there is an ID field immediately available in the newModelItem object.

How does MongoDB ensure that the key isn't a duplicate?

3
  • And there's other: stackoverflow.com/a/5694803 Commented Feb 5, 2020 at 8:46
  • With the internal structure of MongoDB ObjectId you have 16 Million unique ID's which can be generated per second / per process. That should be sufficient for real life. Commented Feb 5, 2020 at 9:51
  • It does not quite answer the question. The ID is being generated locally in my example, not from an index on the Mongo Atlas server. When I call the save method, it just pushes the data to the server with the local ID created. Commented Feb 5, 2020 at 22:27

1 Answer 1

2

Actually that's MongoDB's work to generate (automatically) unique 12-bytes / 24 hex digits IDs. Please have a look at its structure and how it is being created: ObjectId structure

Source: MongoDB ObjectId generation

Sign up to request clarification or add additional context in comments.

1 Comment

So essentially, it's exceedingly rare. The timestamp cannot ensure uniqueness unless counting down to the nanosecond or some insanely small fraction of time if there were mass updates. However, the likelihood of this in combination with the other elements (machine identifier, process id, counter) must make this incredibly unlikely. I feel good enough with that, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.