Mongo DB _id ? Unique for one collection, or all collections?


#1

Hi guys,

Simple question, is the mongodb _id unique for a record in ITS collection, or unique accross all mongodb collections ?

Can i have the same _id in a collection_A, than in a collection_B ?

Thanks a lot,

Happy coding anyway,

B.


#2

Yes, you can have same _id in different collections.


#3

Hey,

Thanks. I’m trying to set related fields like many to one in relationnal DB. Needed to know it to develop this part !

Thanks :slight_smile:


#4

Well, that is more of a MongoDB related question instead of Meteor specific. And being a generic question it is hard to give a concise answer. Have a good read of https://docs.mongodb.com/manual/applications/data-models/. There are many other resources out there with plenty of good generic information: http://bfy.tw/MAtf


#5

The default auto-generated _id of mongodb is most likely unique across collections


#6

Most likely, perhaps there is a chance to get 2 identical _id in 2 different collections ? As said hluz ?

Thanks Hluz, i’ll be checking this later in the day !


#7

#8

As I said, there is no issue at all if you use the same _id values in different collections. You can even specify what _id value you want when you insert a document, as long as it is unique within that collection, and as such ensure two documents in separate collections have the same _id. If you use the automatic generated Mongo ObjectId or the Meteor equivalent (string format, generated by Random.id() function), then the chances of getting a duplicate value are very very low indeed.