randomKek
randomKek

Reputation: 1128

Mongodb database design

I got users, they can create activities and users have friends and each user should be able to get all activities from their friends, a single activity can have multiple users.

Users -> _id, name, friendList
Activity -> _id, description, date, involvedUsers

So an example document would be:

"User theo": 1, theo, array(mike, rutger, tijmen)
"User mike": 2, mike, array(theo, rutger, tijmen)

Activity x: 1, 'having fun with friends', {{todaydatetime}}, array(1, 2)
Activity y: 2, 'going out', {{saturdaydatetime}}, array(1, 2)

So now if "theo" logs in, he has to get that Mike is "going to have fun with friends" same if Mike logs in.

And if they select saturday as date, Mike will get that Theo is going out, and Theo would get the activity that Mike is going out.

How can I accomplish this, I know it's pretty easy in MySql with joins etc, but how can I get all the activities of the users "friendlist" and filtered by a certain date, so for example give me all activities that are happening saturday.

Upvotes: 1

Views: 1102

Answers (2)

Eve Freeman
Eve Freeman

Reputation: 33175

You probably want something like (this is totally untested), and the others are right, if you have too big of arrays (thousands) for your friends lists and your involved, it will probably cause scaling problems:

collection users:
{
  _id: objid, 
  name: "theo", 
  friends: [objid, objid, objid] /* these are user object ids */
}

collection activities:
{
  _id: objid, 
  desc: "having fun with friends", 
  date: new Date(), 
  involved: [objid, objid, objid] /* these are user object ids */
}

I would do ensureIndex on date and involved. See here for more information on indexing array values: http://www.mongodb.org/display/DOCS/Multikeys

db.activities.ensureIndex({date:1});
db.activities.ensureIndex({involved:1});

So to select the users involved in an activity you would do (from the shell):

var start_date = new Date(2012, 1, 14);
var end_date = new Date(2012, 1, 15);
var friends = db.users.findOne(_id: objid for user).friends;
var activities = db.activities.find(
   {
     date: {$gte : start_date},
     date: {$lte : end_date},
     involved : {$in : friends}
   });

Upvotes: 2

lhagemann
lhagemann

Reputation: 1268

If you have to use MongoDB (which isn't a bad choice) you will have to read the docs.

For this particular situation, you are interested in searching within an array:

http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29

Upvotes: 0

Related Questions