2

In mongoDB Many-to-Many Relationship Data Modeling by Mark Starkman, he tries to see how many-to-many relationship can be implemented in the MongoDB database.

enter image description here

He suggests the following code will help us implement many-to-many relationship can be implemented in the MongoDB database:

An example of person's collections:

db.person.insert({
  "_id": ObjectId("4e54ed9f48dc5922c0094a43"),
  "firstName": "Joe",
  "lastName": "Mongo",
  "groups": [
    ObjectId("4e54ed9f48dc5922c0094a42"),
    ObjectId("4e54ed9f48dc5922c0094a41")
  ]
});

db.person.insert({
  "_id": ObjectId("4e54ed9f48dc5922c0094a40"),
  "firstName": "Sally",
  "lastName": "Mongo",
  "groups": [
    ObjectId("4e54ed9f48dc5922c0094a42")
  ]
});

An example of Group collection:

db.groups.insert({
  "_id": ObjectId("4e54ed9f48dc5922c0094a42"),
  "groupName": "mongoDB User",
  "persons": [
    ObjectId("4e54ed9f48dc5922c0094a43"),
    ObjectId("4e54ed9f48dc5922c0094a40")
  ]
});

db.groups.insert({
  "_id": ObjectId("4e54ed9f48dc5922c0094a41"),
  "groupName": "mongoDB Administrator",
  "persons": [
    ObjectId("4e54ed9f48dc5922c0094a43")
  ]
});

The aforementioned solution is alright if a person can belong to groups on the 100s, and vice versa for groups. However, Array of ObjectIds would Not be practical if a person can belong to 1000000 groups, and vice versa for groups.

What would be a better many-to-many solution in MongoDB of the relationship would number 1000000?

2

You can add a third collection, named person_group, being described in that blog picture.

db.person_groups.insert({
  "_id": ObjectId("5e54ed9f48dc5922c0094a42"),
  "groupId": ObjectId("4e54ed9f48dc5922c0094a43"),
  "personId": ObjectId("4e54ed9f48dc5922c0094a44")
});
  • 1
    Thanks.However, my only concern now is that it might be better to just use a typical Relational Database (RDBMS). Aren't "bridge"-like entities like person_groups more suitable for the Relational Database (RDBMS) world? Wouldn't "bridge"-like entities like person_groups reduce speed performance in MongoDB databases? – crazyTech Aug 28 '17 at 14:51
  • 2
    RDBMS queries may be easier, but there is nothing wrong about using bridges in MongoDB. The blog makes a case about using few groups. If you need billions, that may be the best way. When your database get that big, you will need to think about sharding the database. Then, depending on how you set the shard key, you can get maximum performance. Finally, when you have that many records, you need to rethink the program. For example, the user can't handle billions in his screen, most of the time, you never have to query the entire dataset, only what you need. – Marcos Zolnowski Aug 28 '17 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.