Created
September 7, 2011 18:56
-
-
Save mstarkman/1201392 to your computer and use it in GitHub Desktop.
mongoDB Many-to-Many Data Modeling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
] | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
db.person.ensureIndex({"groups": 1}); | |
db.groups.ensureIndex({"persons": 1}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
] | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get all persons in the "mongoDB User" group | |
db.person.find({"groups": ObjectId("4e54ed9f48dc5922c0094a42")}); | |
// Get all persons in the "mongoDB Administrator" group | |
db.person.find({"groups": ObjectId("4e54ed9f48dc5922c0094a41")}); | |
// Get all groups for "Joe Mongo" | |
db.groups.find({"persons": ObjectId("4e54ed9f48dc5922c0094a43")}); | |
// Get all groups for "Sally Mongo" | |
db.groups.find({"persons": ObjectId("4e54ed9f48dc5922c0094a40")}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment