Reputation: 3358
So somehow MongoDB does not support autoincrement for scaling purposes.
My question is what then do I use for constraints?
Should I use Object-id as a constraint for finding something? Isn't that going to be slow? (It's a 12-BYTE
field!)
Should I use a unique key as a sort of 'primary-key'? e.g. Books.find('actual-author-name')
? Is this going to be faster?
Basically, what is the general/accepted way of doing this?
Upvotes: 0
Views: 1695
Reputation: 69663
The point of auto-increment is usually to auto-generate key-values which are guaranteed to be unique.
The MongoDB ObjectID
s can fullfill this role by being not just unique to the collection but even globally unique. They are also in ascending order, because they begin with the current timestamp.
They are not guaranteed to be consecutive, but Auto-increment columns in SQL databases aren't either, because when you delete a record, that ID will not be reused.
Note that the _id field of MongoDB doesn't necessarily need to be an ObjectID. You can also assing any other data to it. So when your datasets already have unique identifiers, you can use these by populating the _id manually before inserting the documents. The _id field doesn't even have to be a primitive value. It can even be an object. So you can have multi-field primary keys like this:
_id: { first_name = "John", last_name = "Smith" }
Upvotes: 0
Reputation: 5993
You can use auto-incrementing fields. See this code in MongoDB's documentation:
http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/#a-counters-collection
This is an opinion-based answer to a broad question, and the code I gave you uses another collection to do what it does, but my point is, you can do auto-incrementing fields.
Upvotes: 1
Reputation: 36784
If you already have a suitable key, please use that as _id field for correlation between collections. You can also rely on the 12 byte field, as it's not really that much. Please also check whether it is not easier to use embedded documents instead to avoid having to make links all together—that is often the preferred solution in a document database like MongoDB.
Upvotes: 1