3

I'm coming from CodeIgniter/MySQL to Laravel/MongoDB application.

My app structure is:

User (model)

  • id
  • firstname
  • lastname
  • age
  • gender
  • facebook_id
  • facebook_data
  • google_id
  • google_data

Test (model)

  • user_id
  • type
  • title
  • status
  • result

In MongoDB, should I have one USER collection with many TESTS inside, or put TESTS outside the USER collections?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Leabdalla
  • 656
  • 9
  • 19
  • the question is exactly about drawing the collections structure. when is a bad idea put all user data inside user collection? when separate into different collections/models? – Leabdalla Mar 05 '13 at 17:58
  • you might find [this answer](http://stackoverflow.com/a/5864000/727208) somewhat relevant – tereško Mar 05 '13 at 22:28

1 Answers1

2

Data modelling considerations

This is covered in some detail in the mongoDB documentation - though it's not a mongoDB specific question.

There is no global right or wrong answer, but as a rule if you are considering creating an array of embedded documents e.g.:

db.posts.findOne();
{
    title: "Some Post",
    comments: [
        {
            _id: ObjectId("x"),
            author_id: ObjectId("y"),
            body: "z",
            created: Date()
        },
        {
            _id: ObjectId("a"),
            author_id: ObjectId("b"),
            body: "c",
            created: Date()
        },
    ]
}

... this'll work well, only with a trivial amount of data. For non-trivial amounts of data it can be quite restrictive/problematic. For example, if there are hundreds of comments per post - it's difficult to paginate through them efficiently. As such, do not create arrays of embedded documents if you expect the number of embedded documents to be significant - instead use a separate collection.

Example schema for data in the question

You could consider the following schema for your data:

Users:

_id: objectId
firstname
lastname
age
gender
facebook: {
    id: longint/string
    locale:
    ...
}
google: {
    id: string
    age:
    ...
}

Test

_id: objectId
user_id: objectId
type
title
status
result

The facebook and google objects hold "data" as written in the question - but appart from that you have an ordinary user has many test, test belongsTo user data relationship. This permits any number of tests, and does not have any real disadvantages given the information in the question.

Community
  • 1
  • 1
AD7six
  • 63,116
  • 12
  • 91
  • 123