Pablo Politi
Pablo Politi

Reputation: 28

Relation N to N mongodb. Embedded or reference?

I'm newbie in mongodb. Suppose I have the following:

In this case, I have a relation N to N between Posts an tags. Because 1 Post could be have several tags associated and vice versa.

Post

{
    "_id" : ObjectId("508d27069cc1ae293b36928d"),
    "title" : "This is the title",
    "body" : "This is the body text.",
    "tags" : [
        "chocolate",
        "spleen",
        "piano",
        "spatula"
    ],
    "created_date" : ISODate("2012-10-28T12:41:39.110Z"),
    "author_id" : ObjectId("508d280e9cc1ae293b36928e"),
    "category_id" : ObjectId("508d29709cc1ae293b369295"),
    "comments" : [
        {
            "subject" : "This is coment 1",
            "body" : "This is the body of comment 1.",
            "author_id" : ObjectId("508d345f9cc1ae293b369296"),
            "created_date" : ISODate("2012-10-28T13:34:23.929Z")
        },
        {
            "subject" : "This is coment 2",
            "body" : "This is the body of comment 2.",
            "author_id" : ObjectId("508d34739cc1ae293b369297"),
            "created_date" : ISODate("2012-10-28T13:34:43.192Z")
        },
        {
            "subject" : "This is coment 3",
            "body" : "This is the body of comment 3.",
            "author_id" : ObjectId("508d34839cc1ae293b369298"),
            "created_date" : ISODate("2012-10-28T13:34:59.336Z")
        }
    ]
}

Let's say I have to change a specific tag, for instance: replace "chocolate" by "choco". Probably, There will have a lot of posts with the tag "chocolate".

Is this approach embedded the correct one or Do I have to implement reference?

Upvotes: 0

Views: 156

Answers (1)

If you expect that a value that is used in multiple locations may need to be changed you'll need to use it by reference. IE in your case if you have a ton of posts with the chocolate and you need to replace it with choco, it will be very inefficient (and a little bit risky) if the tags are embedded. However if its all done by reference you just need to change chocolate to choco in one place.

StackOverflow actually does this. Question tags may be renamed and it will instantly rename all the instances of the tag. This is done easily by StackOverflow though because they use relational SQL databases in the backed.

Which leads me to my final point - if you expect to need a lot of reference data you should really reconsider using Mongo. When your data has a lot of reference relations, you probably want to use a relational database.

Upvotes: 1

Related Questions