Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.4k views
in Technique[技术] by (71.8m points)

MongoDB Embedding alongside referencing

There is a lot of content of what kind of relationships should use in a database schema. However, I have not seen anything about mixing both techniques.? The idea is to embed only the necessaries attributes and with them a reference. This way the application have the necessary data for rendering and the reference for the updating methods.

The problem I see here is that the logic for handle any CRUD operations becomes more tricky because its mandatory to update multiples collections however I have all the information in one single read.

Basic schema for a page that only wants the students names of a classroom:

CLASSROOM COLLECTION
{"_id": ObjectID(),
 "students": [{"studentId" : ObjectID(),
                   "name" : "John Doe",
                   },
                   ...
                 ]
}

STUDENTS COLLECION
{"_id": ObjectID(),
 "name" : "John Doe",
 "address" : "...",
 "age" : "...",
 "gender": "..."
}

I use the students' collection in a different page and there I do not want any information about the classroom. That is the reason not to embed the students.

I started to learning mongo a few days ago and I don't know if this kind of schema bring some problems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can embed some fields and store other fields in a different collection as you are suggesting.

The issues with such an arrangement in my opinion would be:

  1. What is the authority for a field? For example, what if a field like name is both embedded and stored in the separate collection, and the values differ?

  2. Both updating and querying become awkward as you need to do it differently depending on which field is being worked with. If you make a mistake and go in the wrong place, you create/compound the first issue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...