How do I design a scheme such this in MongoDB? I think there are no foreign keys!
相关问题
- MongoDB can not create unique sparse index (duplic
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- php PDO::FETCH_ASSOC doesnt detect select after ba
First, to clarify some naming conventions. MongoDB uses
collections
instead oftables
.Take the following model:
Clearly Jane's course list points to some specific courses. The database does not apply any constraints to the system (i.e.: foreign key contstraints), so there are no "cascading deletes" or "cascading updates". However, the database does contain the correct information.
In addition, MongoDB has a DBRef standard that helps standardize the creation of these references. In fact, if you take a look at that link, it has a similar example.
To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.
You may be interested in using a ORM like Mongoid or MongoMapper.
http://mongoid.org/docs/relations/referenced/1-n.html
In a NoSQL database like MongoDB there are not 'tables' but documents. Documents are grouped inside Collections. You can have any kind of document – with any kind of data – in a single collection. Basically, in a NoSQL database it is up to you to decide how to organise the data and its relations, if there are any.
What Mongoid and MongoMapper do is to provide you with convenient methods to set up relations quite easily. Check out the link I gave you and ask any thing.
Edit:
In mongoid you will write your scheme like this:
Edit:
You can use that ObjectId in order to do relations between documents.
We can define the so-called
foreign key
in MongoDB. However, we need to maintain the data integrity BY OURSELVES. For example,The
courses
field contains_id
s of courses. It is easy to define a one-to-many relationship. However, if we want to retrieve the course names of studentJane
, we need to perform another operation to retrieve thecourse
document via_id
.If the course
bio101
is removed, we need to perform another operation to update thecourses
field in thestudent
document.More: MongoDB Schema Design
The document-typed nature of MongoDB supports flexible ways to define relationships. To define a one-to-many relationship:
Embedded document
Example:
Child referencing
Like the
student
/course
example above.Parent referencing
Suitable for one-to-squillions, such as log messages.
Virtually, a
host
is the parent of alogmsg
. Referencing to thehost
id saves much space given that the log messages are squillions.References:
From The Little MongoDB Book
So,
If its a RESTful API data, replace the course id with a GET link to the course resource