开发者

MongoDB (Mongoid) many-to-many relationship with additional data (additional fields)

Let's say that my models are User and Project. Each user can be assigned to many projects and each project can have many users assigned. This is a typical many to many relationship and could be stored as (source):

# The user document.
{
  "_id" : ObjectId("4d3ed089fb60ab534684b7e9"),
  "project_ids" : [ ObjectId("4d3ed089fb60ab534684b7f2") ]
}

# The project document.
{
  "_id" : ObjectId("4d3ed089fb60ab534684b7f2"),
  "user_ids" : [ ObjectId("4d3ed089fb60ab534684b7e9") ]
}

The problem is, I would like to assign more data describing this relationship, e.g. a role that the user has in the project (admin, manager, etc.). In a RDBMS I would just add an additional column to the join table. In MongoDB, I really don't know how to go about this.

Should I create an additional embedded document in e开发者_Python百科ither User or Project? I was thinking about something like this:

# The project document.
{
  "_id" : ObjectId("4d3ed089fb60ab534684b7f2"),
  "assigned_users" : [
    { user_id: ObjectId("4d3ed089fb60ab534684b7e9"), role: "admin" },
    ...
  ]
}

But I guess a query for getting all user's projects would become quite complicated, right?

I'm using Mongoid, but would be grateful for any general solution (and then I'll figure out how to map this to Mongoid ;) Also, I can't change the database to RDBMS.


How about storing everything you know about a User inside the Users collection?

{
  "_id": ObjectID("..."),
  "projects": [
    { "role": "admin", "project_id": ObjectId("...") },
    { "role": "manager", "project_id": ObjectId("...") }
  ]
}

Querying would take place on the Users collection.

// find all admins on a project, for example
db.Users.find( { "projects" : 
                  { "role" : "admin", "project_id": ObjectId("...") } })
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜