Question

i have an application with basically has 3 objects:

User, Company, Address where a User can belong to a Company, and a Company object can have number of Addresses and an Address object can have one to many users that belong to it.

From a mangodb, nosql design, what would be more efficient, so that the application can list all users belonging to a company and also to an address?

Currently, my User document is like:

> db.users.find().pretty()
{
    "__v" : 1,
    "_id" : ObjectId("532b039c17fc6100001a8737"),
    "active" : true,
    "email" : "norman@khine.net",
    "groups" : "member",
    "lockUntil" : 0,
    "loginAttempts" : 0,
    "name" : "Norman Khine",
    "password" : "$2a$10$EqptX.RRmsk0.FgFRJOpYe9swH0y.lBrgUsg/IatxErjYPm9bT4yq",
    "provider" : [
        "github",
        "local"
    ],
    "surname" : "",
    "tokenExpires" : 1395418101786,
    "tokenString" : "xX-gA29ep27Yv_Cg3OHxLLSfURfVYnAloEncWsJeOf3Er8HvoVWaSvCSSddRFHQY"
}

Will it be better to have:

"company": ["_id","_id"...] # this way a user can belong to one or many companies "address": ["_id", "_id"...] # this way a user can belong to one or many addresses

or shall i put each user_id within the "company" and "address" schema?

any advice much appreciated.

Was it helpful?

Solution

Well, it simply depends on what your application is used to load normally. If your application is very user-centric, you reference (*) the companies and addresses within the user document. If you normally show company information, reference the users in the company. And if you have an address centric.. well, I think you know what I mean ;)

(*) References in NoSQL databases CAN have impacts on the performance. This is the reason for something named "pre-joining". Simply put together the data, you need most of the times at one time. Simple example: If you show the user information in your application, you most likely want also the name of the company, he is working for, on the screen. If you only reference the company, you need an additional lookup for the company just to get out the company's name. THe idea is now, to put the reference about the company together with the most needed data into the user's document. Or - if you only have companies in relation with users and company information will never be maintained on its own, then simply put the whole company data into the user's document. MongoDB will then ensure, that you can load the document with no additional disk lookups.

If you have to much references in your documents, it is most likely a sign for an outstanding redesign of your document structure. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top