user4182696
user4182696

Reputation:

MongoDb - Embedding or reference?

I come from SQL relation world, and have a question that involves mongodb schema design.

The reality that i need to represent contains: Users, and monthly reports (with multiple daily reports).

I want to figure out if in mongodb, is better to embedded reports objects into the Users collection, or to have 2 separate collection referenced by id.

Embedded solution:
User:{
     name:
     surname:
     monthlyReports: [{
                month: "January 2014"
                dailyReport: [{
                      day: 1
                      singleReport: [
                         { report1}, {report2}, ...
                      ]
                }, {
                     day: 2
                     singleReport: [ 
                         { report1}, {report2}, ...
                     ]
                }
                ]
           },
           {
            /*
               february 2014
               Day 1
               Day 2 ...
             */
           } ...
     ]
}

Referenced solution:
Users:{
     name:
     surname:
     monthlyReports: [
             id_reportMonth1, id_reportMonth2, ...
     ]
}

MonthlyReport: {
       id:
       month:
       dailyReport: [{
                    day: 1
                    singleReport: [
                            { report1 }, { report2 } ...
                    ]
               },
               {
                } ....
       ]
}

For single user, i need to retrive single daily report, monthly report, and total report.

I think that in embedded solution, querying is more simple, but create large object in a long period.

Another possibility: Create 3 referenced collection: User, monthlyReport, dailyReport.

What is the better way to do it? Someone has suggested?

Upvotes: 1

Views: 273

Answers (1)

Protostome
Protostome

Reputation: 6039

Mongo wrote an excellent 3 parts blog post about it: http://blog.mongodb.org/post/87200945828/6-rules-of-thumb-for-mongodb-schema-design-part-1

Bottom line: it depends on the use.

You need to consider two factors (ref: mongodb blog post) :

  1. Will the entities on the “N” side of the One-to-N ever need to stand alone?
  2. What is the cardinality of the relationship: is it one-to-few; one-to-many; or one-to-squillions?

Based on these factors, you can pick one of the three basic One-to-N schema designs:

  1. Embed the N side if the cardinality is one-to-few and there is no need to access the embedded object outside the context of the parent object
  2. Use an array of references to the N-side objects if the cardinality is one-to-many or if the N-side objects should stand alone for any reasons
  3. Use a reference to the One-side in the N-side objects if the cardinality is one-to-squillions

Hope this helps.

Upvotes: 1

Related Questions