1
votes

The MongoDB docs show an example of a one to many relationship...

(Abbreviated...)

Model One-to-Many Relationships with Document References

 // Publisher.
 {
    _id: "oreilly",
    name: "O'Reilly Media",
 }

 // Book.
 {
    _id: 123456789,
    title: "MongoDB: The Definitive Guide",
    publisher_id: "oreilly"
 }

 // Book.
 {
    _id: 234567890,
    title: "50 Tips and Tricks for MongoDB Developer",
    publisher_id: "oreilly"
 }

Why is the publisher _id a logical, human-readable name while the book _ids appear to be generated surrogate keys?

Wouldn't all _ids be generated values?

Is it conventional in MongoDB to sometimes use the data itself as a unique key and sometimes not?

If so, when do we use ordinary names ("mary", "joe", "exxon"), and when do we prefer generated values?

1

1 Answers

1
votes

Wouldn't all _ids be generated values?

MongoDB auto-generates _id only when it is not provided by the user.

Is it conventional in MongoDB to sometimes use the data itself as a unique key and sometimes not?

Yes, The data can be used as the key. The _id value has to be unique in a collection to correctly identify a document. Any parameter in the document can be set as the _id if it satisfies the above criteria. When the _id is not unique in a collection the duplicate key error is thrown.

If so, when do we use ordinary names ("mary", "joe", "exxon"), and when do we prefer generated values?

We prefer a generated _id when there is no parameter(or parameter groups), that uniquely identify the document. For example, using the name of a person will not work because, there might come a situation to add another person with the same name. However, consider a books ISBN number, it uniquely identifies a book. Such parameters can be used as _id.

Additional Notes:

  • The auto-generated _id has embedded timestamp value (which may be of use).
  • No need to worry about duplicate values with auto-generated _id.
  • However, an user specified _id value may be more application/domain specific.