Andrew Grothe
Andrew Grothe

Reputation: 2374

NoSQL optimization strategy

Looking for some input on the following. Hopefully this isn't too subjective for the moderators.

Just started playing with deployd.com BaaS API and have the following scenario.

If an mobile app was to have a Group object and a User, where a User could belong to many Groups and Groups have many Users (many-to-many relationship) I could design this several ways with two that I'm considering:

A)

Users [{
  id: 1,
  groups : {1,2,3,4}
}]

Groups [{
  id: 1,
  users : {1,2,3,4}
}]

And

B)

Users [{
   id: 1
}]

Groups [{
   id: 1
}]

UserGroups [{
   id: 1,
   group: 1,
   user: 1,
 },{
   id: 2
   group: 1,
   user: 2,
}]

I'm leaning towards B as I can store meta-data (date a user joined the group, etc) but this seems to be more a RDBMS method and I'm wondering if I will lose any of the benefits of NoSQL by trying to create such relations.

Hypothetically speaking this mobile app would be used by thousands of mobile users simultaneously and hence choosing NoSQL versus RDBMS in the first place.

Upvotes: 0

Views: 947

Answers (1)

Philipp
Philipp

Reputation: 69663

B) is not a good idea. MongoDB doesn't do joins, so any operation which needs multiple collections means multiple subsequent queries, which is much slower than a database-internal JOIN in a relational database. That means you should store relations in the documents themself.

When you want to store meta-information, keep in mind that arrays can't just store primitive values. They can also store objects. Example:

{
    id:1,
    name:"Bob",
    groups: [
        { name: "nice people",
          position: "member",
          joined: ISODate(2013, 12, 3)
        } ,
        { name: "evil people",
          position: "admin",
          joined: ISODate(2012, 11, 22)
        }

    ]
}

It might be a good idea to store enough meta-information so that many common queries can be fulfilled without querying the referenced objects. When you want to show a list of groups when someone looks up a users profile, and you store all the group information you need in that overview in the users-document, you avoid having to do a second query to retrieve the group-documents.

Upvotes: 1

Related Questions