3

In JPA using SQL backend, 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

2 Answers 2

3

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"
}
2
  • I meant to suggest that you (1) remove the words "as suggested", and (2) replace "Database references" with "DBRefs". This would make your answer more helpful. I have removed my previous comment to avoid confusion.
    – jtoberon
    Sep 14, 2011 at 18:13
  • I found this approach perfect for my application. Thanks for the help! Sep 19, 2011 at 19:41
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.