which way will be more efficient?

I am more used to MySQL but I decided to go MongoDB for this project. Basically it's a social network.

I have a posts collection where documents currently look like this:

{
    "text": "Some post...",
    "user": "3j219dj21h18skd2" // User's "_id"
}

I am looking to implement a replies system. Will it be better to simply add an array of liking users, like so:

{
    "text": "Some post...",
    "user": "3j219dj21h18skd2", // User's "_id"
    "replies": [
    {
            "user": "3j219dj200928smd81",
            "text": "Nice one!"
        },
        {
            "user": "3j219dj2321md81zb3",
            "text": "Wow, this is amazing!"
        }
    ]
}

Or will it be better to have a whole separate "replies" collection with a unique ID for each reply, and then "link" to it by ID in the posts collection?

I am not sure, but feels like the 1st way is more "NoSQL-like", and the 2nd way is the way I would go for MySQL.

Any inputs are welcome.


This is a typical data modeling question in MongoDB. Since you are planning to store just the _id of the user the answer is definitely to embed it because those replies are part of the post object.

If those replies can number in the hundreds or thousands and you are not going to show them by default (for example, you are going to have the users click to load those comments) then it would make more sense to store the replies in a separate collection.

Finally, if you need to store more than the user _id (such as the name) you have to think about maintaining the name in two places (here and in the user maintenance page) as you are duplicating data. This can be manageable or too much work. You have to decide.

链接地址: http://www.djcxy.com/p/88754.html

上一篇: HTML与XHTML

下一篇: 哪种方式会更有效率?