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?

Adam Johnston
  • 228
  • 1
  • 8
  • And there's other: https://stackoverflow.com/a/5694803 – Rytis Alekna Feb 05 '20 at 08: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. – Wernfried Domscheit Feb 05 '20 at 09: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. – Adam Johnston Feb 05 '20 at 22:27

1 Answers1

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

Hlib Derbenov
  • 916
  • 1
  • 7
  • 15
  • 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. – Adam Johnston Feb 05 '20 at 22:30