What would be a better many-to-many solution in MongoDB of the relationship would number 1000000? 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.


  


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?
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")
});