Aslan Almaniyazov
Aslan Almaniyazov

Reputation: 93

How store data (documents) in MongoDB

I'm studying mongodb and want to build a little database for web blogs page. It is known that in mongo we use collections and documents, in opposite, of tables and records.

I have 2 documents (entities): User (id, nikname) and Publication (id, title ...) In relational database we would have user_id as column inside "Publication" and this would mean that users able to have many publications.

Example1

User 
{
  id: "123456",
  nikname: "cool guy",
  publications: [   
        {
            id: "some id1",
            title: "some title111",
            text: "bla bla bla",
            // any fields
        },
        {
            id: "some id2",
            title: "some title222",
            text: "bla bla bla",
            // any fields
        },
        ....
    ]
}

Publication 
{
    id: "some id",
    title: "some title",
    text: "bla bla bla",
    // any fields       
} 

In example above, each user has own array of publications.

My question is: Is this a good way to do like this? What if one user will have 1000 publications?

Moreover, if each user has an own publications then why we need to store publications table (in MONGO it is called COLLECTION) outside the user as separate entity.

I was also thinking about a storing publication ids inside of user.

Example2

User 
{
  id: "123456",
  nikname: "cool guy"
}

Publication 1
{
    id: "some id",
    title: "some title",
    text: "bla bla bla",
    // any fields   

    USER_ID: 123456 
} 

Publication 2
{
    id: "some id",
    title: "some title",
    text: "bla bla bla",
    // any fields

    USER_ID: 123456     
} 

But Example2 does not differ from relational approach...

So What way will be better ?

In short, would like to know opinions of guys who worked with mongo.

Upvotes: 1

Views: 261

Answers (1)

Pubudu Jayawardana
Pubudu Jayawardana

Reputation: 2365

In Mongo there are 3 ways you can design your model relationships.

  • One to One
  • One to Many (Embedded Docs) : your example 1
  • One to Many (Document References) : your example 2

Rule of thumb is that you need to consider your data retrieval pattern of your application.

For example, if your application need to fetch Publication related to a particular user heavily, you can go for example 1 and you don't need to maintain publications in a separate collection (unless application requires it). Having a lot of sub documents are not a problem as far as a single document will not exceed the hard limits.

Example 2 of your one good if your application need to query by publications as well as user (similar to a relation model). However I see this is a not a optimized solution.

Some resource: https://docs.mongodb.com/manual/applications/data-models-relationships/

Upvotes: 1

Related Questions