In JPA using SQL backend,开发者_JAVA百科 the embedded tables are updated automatically. Is there a mechanism in NoSQL (MongoDB) to achieve the same?
Here is an example of what I am trying to achieve: Tables:Student
Student details @OnetoMany Course Details (from another course table)
In JPA and SQL, if the Course Details table is updated the changes are reflected across all the Students referring to it.
In MongoDB instead of using joins the document is embedded inside it. How do we solve this problem in MongoDB?
Thanks, Sam
In short, no. It's also a bit of an apples and oranges question. MongoDB is an SQL replacement in the loosest sense of the word. They're both databases. JPA is an ORM layer on top of that that can do things like keeping your 1:N and N:M relationships consistent under the hood. There is currently no MongoDB ORM layer that implements JPA or something close to it.
That said, within the context of a NoSQL database like mongo your schema is not correct. You should not be embedding documents with content that is reused (in most cases, exceptions involve performance optimization where you sacrifice things like normalization for data duplication and thus performance).
In this case you want a seperate course details collection and store an array of _id values of that course detail in your student document. That way you can modify this collection seperately without having to keep track of mutations of the course details documents.
Do not use DBRefs references for this. DBRefs are not the appropriate tool for ID references to documents of a known type. Use simple _id references instead.
So, the TL;DR version :
- Put course detail documents in seperate collection
- Embed only an array of _id's to course detail documents in your student
Example :
db.students {
_id: ..,
name: Willy Wonka,
courses: [..,..,..]
}
db.courses {
_id: ..,
course: "MongoDB for Dummies"
}
You can use a reference instead of an embedded document. Then, there's only one copy of the Course data, and all Students must refer to the same information by definition.
精彩评论