ChatGPT解决这个技术问题 Extra ChatGPT

MongoDB relationships: embed or reference?

I'm new to MongoDB--coming from a relational database background. I want to design a question structure with some comments, but I don't know which relationship to use for comments: embed or reference?

A question with some comments, like stackoverflow, would have a structure like this:

Question
    title = 'aaa'
    content = bbb'
    comments = ???

At first, I want to use embeded comments (I think embed is recommended in MongoDB), like this:

Question
    title = 'aaa'
    content = 'bbb'
    comments = [ { content = 'xxx', createdAt = 'yyy'}, 
                 { content = 'xxx', createdAt = 'yyy'}, 
                 { content = 'xxx', createdAt = 'yyy'} ]

It clear, but I'm worried about this case: If I want to edit a specified comment, how do I get its content and its question? There is no _id to let me find one, nor question_ref to let me find its question. (I'm so newbie, that I don't know if there's any way to do this without _id and question_ref.)

Do I have to use ref not embed? Then I have to create a new collection for comments?

All Mongo objects are created with an _ID, whether you create the field or not. So technically each comment will still have an ID.
@RobbieGuilfoyle not true-- see stackoverflow.com/a/11263912/347455
I stand corrected, thanks @pennstatephil :)
What he maybe means is that all mongoose objects are created with an _id for those who use this framework – see mongoose subdocs
A very good book for learning mongo db relationships is "MongoDB Applied Design Patterns - O'Reilly". Chapter one, talk about this decision, to embed or reference?

D
Dima Lituiev

This is more an art than a science. The Mongo Documentation on Schemas is a good reference, but here are some things to consider:

Put as much in as possible The joy of a Document database is that it eliminates lots of Joins. Your first instinct should be to place as much in a single document as you can. Because MongoDB documents have structure, and because you can efficiently query within that structure (this means that you can take the part of the document that you need, so document size shouldn't worry you much) there is no immediate need to normalize data like you would in SQL. In particular any data that is not useful apart from its parent document should be part of the same document.

Separate data that can be referred to from multiple places into its own collection. This is not so much a "storage space" issue as it is a "data consistency" issue. If many records will refer to the same data it is more efficient and less error prone to update a single record and keep references to it in other places.

Document size considerations MongoDB imposes a 4MB (16MB with 1.8) size limit on a single document. In a world of GB of data this sounds small, but it is also 30 thousand tweets or 250 typical Stack Overflow answers or 20 flicker photos. On the other hand, this is far more information than one might want to present at one time on a typical web page. First consider what will make your queries easier. In many cases concern about document sizes will be premature optimization.

Complex data structures: MongoDB can store arbitrary deep nested data structures, but cannot search them efficiently. If your data forms a tree, forest or graph, you effectively need to store each node and its edges in a separate document. (Note that there are data stores specifically designed for this type of data that one should consider as well) It has also been pointed out than it is impossible to return a subset of elements in a document. If you need to pick-and-choose a few bits of each document, it will be easier to separate them out.

Data Consistency MongoDB makes a trade off between efficiency and consistency. The rule is changes to a single document are always atomic, while updates to multiple documents should never be assumed to be atomic. There is also no way to "lock" a record on the server (you can build this into the client's logic using for example a "lock" field). When you design your schema consider how you will keep your data consistent. Generally, the more that you keep in a document the better.

For what you are describing, I would embed the comments, and give each comment an id field with an ObjectID. The ObjectID has a time stamp embedded in it so you can use that instead of created at if you like.


I'd like to add to the OP question: My comments model contains the user name and link to his avatar. What would be the best approach, considering a user can modify his name/avatar?
Regarding 'Complex data structures', it seems it is possible to return a subset of elements in a document using the aggregation framework (try $unwind).
Errr, This technique was either not possibel or not widely known in MongoDB at the beginning of 2012. Given the popularity of this question, I would encourage you to write your own updated answer. I'm afraid I've stepped away from active development on MongoDB and I am not in a good position to address you comment within my original post.
16MB = 30 million tweets? ths menas about 0,5 byte per tweet?!
Yes, it appears I was off by a factor of 1000 and some people find this important. I will edit the post. WRT 560bytes per tweet, when I rote this in 2011 twitter was still tied to text messages and Ruby 1.4 strings; in other words still ASCII chars only.
y
ywang1724

In general, embed is good if you have one-to-one or one-to-many relationships between entities, and reference is good if you have many-to-many relationships.


can you please add a reference link? Thanks.
How do you find a specific comment with this design of one to many?
Embeddings are not the way to go in the one-to-many if the many in this case is a large number. In that case reference or partial embeddings should be used instead
S
Silom

Well, I'm a bit late but still would like to share my way of schema creation.

I have schemas for everything that can be described by a word, like you would do it in the classical OOP.

E.G.

Comment

Account

User

Blogpost

...

Every schema can be saved as a Document or Subdocument, so I declare this for each schema.

Document:

Can be used as a reference. (E.g. the user made a comment -> comment has a "made by" reference to user)

Is a "Root" in you application. (E.g. the blogpost -> there is a page about the blogpost)

Subdocument:

Can only be used once / is never a reference. (E.g. Comment is saved in the blogpost)

Is never a "Root" in you application. (The comment just shows up in the blogpost page but the page is still about the blogpost)


C
Community

I came across this small presentation while researching this question on my own. I was surprised at how well it was laid out, both the info and the presentation of it.

http://openmymind.net/Multiple-Collections-Versus-Embedded-Documents

It summarized:

As a general rule, if you have a lot of [child documents] or if they are large, a separate collection might be best. Smaller and/or fewer documents tend to be a natural fit for embedding.


How much is a lot? 3? 10? 100? What's large? 1kb? 1MB? 3 fields? 20 fields? What is smaller / fewer?
That's a good question, and one I don't have a specific answer for. The same presentation included a slide that said "A document, including all its embedded documents and arrays, cannot exceed 16MB", so that could be your cutoff, or just go with what seems reasonable/comfortable for your specific situation. In my current project, the majority of embedded documents are for 1:1 relationships, or 1:many where the embedded documents are really simple.
See also the current top comment by @john-f-miller, which while also not providing specific numbers for a threshold does contain some additional pointers that should help guide your decision.
Have a look at the below link from official Mongo website. It gives great, clear insight and describes more explicitly how much is 'a lot'. For example: If there are more than a couple of hundred documents on the "many" side, don't embed them; if there are more than a few thousand documents on the "many" side, don't use an array of ObjectID references. mongodb.com/developer/article/…
B
Bonjour123

Actually, I'm quite curious why nobody spoke about the UML specifications. A rule of thumb is that if you have an aggregation, then you should use references. But if it is a composition, then the coupling is stronger, and you should use embedded documents.

And you will quickly understand why it is logical. If an object can exist independently of the parent, then you will want to access it even if the parent doesn't exist. As you just can't embed it in a non-existing parent, you have to make it live in it's own data structure. And if a parent exist, just link them together by adding a ref of the object in the parent.

Don't really know what is the difference between the two relationships ? Here is a link explaining them: Aggregation vs Composition in UML


Why -1 ? Please give an explanation that would clarify the reason
Your view about embedded and references actually gave me one more strong point to defend my view in the future. But in some cases if you are using composition and embedding like you said, the memory usage will increase for large docs even if we use projections to limit the fields. So, it is not entirely based on relationships. To actually increase the performance of read queries by avoiding reading whole doc, we can use references even though the design has composition. Maybe that's why -1 I guess.
Yes, you're right, one should also base his strategy depending on how he's going to retrieve the data, and the size of the embedded documents, +1
G
Gates VP

If I want to edit a specified comment, how to get its content and its question?

You can query by sub-document: db.question.find({'comments.content' : 'xxx'}).

This will return the whole Question document. To edit the specified comment, you then have to find the comment on the client, make the edit and save that back to the DB.

In general, if your document contains an array of objects, you'll find that those sub-objects will need to be modified client side.


this won't work if two comments have identical contents. one might argue that we could also add author to the search query, which still wouldn't work if the author made two identical comments with same content
@SteelBrain: if he had kept the comment index, dot notation might help. see stackoverflow.com/a/33284416/1587329
I don't understand how this answer has 34 upvotes, the second multiple people comment the same thing the whole system would break. This is an absolutely terrible design and should never be used. The way @user does it is the way to go
@user2073973 So what's the recommended way to fetch such comments?
D
David Beech

Yes, we can use the reference in the document.To populate the another document just like sql i joins.In mongo db they dont have joins to mapping one to many relationship document.Instead that we can use populate to fulfill our scenario..

var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, plain object, multiple plain objects, or all objects returned from a query. Let's look at some examples.

Better you can get more information please visit :http://mongoosejs.com/docs/populate.html


Mongoose will issue a seperate request for each populated field. This is different to SQL JOINS as they are performed on the server. This includes extra traffic between the app server and the mongodb server. Again, you might consider this when you're optimizing. Nevertheless, your anwser is still correct.
f
finspin

I know this is quite old but if you are looking for the answer to the OP's question on how to return only specified comment, you can use the $ (query) operator like this:

db.question.update({'comments.content': 'xxx'}, {'comments.$': true})

this won't work if two comments have identical contents. one might argue that we could also add author to the search query, which still wouldn't work if the author made two identical comments with same content
@SteelBrain: Well played sir, well played.
r
r7r

MongoDB gives freedom to be schema-less and this feature can result in pain in the long term if not thought or planned well,

There are 2 options either Embed or Reference. I will not go through definitions as the above answers have well defined them.

When embedding you should answer one question is your embedded document going to grow, if yes then how much (remember there is a limit of 16 MB per document) So if you have something like a comment on a post, what is the limit of comment count, if that post goes viral and people start adding comments. In such cases, reference could be a better option (but even reference can grow and reach 16 MB limit).

So how to balance it, the answer is a combination of different patterns, check these links, and create your own mix and match based on your use case.

https://www.mongodb.com/blog/post/building-with-patterns-a-summary

https://www.mongodb.com/blog/post/6-rules-of-thumb-for-mongodb-schema-design-part-1


That's a good rule of thumb +1. If you have a lot of related data like comments. There can be millions of comments and you don't want to show them all so obviously it's better to store it in post_comments collection or something like that.
C
Community

If I want to edit a specified comment, how do I get its content and its question?

If you had kept track of the number of comments and the index of the comment you wanted to alter, you could use the dot operator (SO example).

You could do f.ex.

db.questions.update(
    {
        "title": "aaa"       
    }, 
    { 
        "comments.0.contents": "new text"
    }
)

(as another way to edit the comments inside the question)