We need to be able to quickly perform queries across the set of a user's friends and friends of friends. This would be relatively straightforward in a relational database, but I'm somewhat stuck on the best way to accomplish it in MongoDB. We store the user IDs of a user's friends in an array in the user document, so the obvious solution is to do this:
While straightforward, this seems like a huge amount of back and forth, as compared to what we could do with a join in a relational database. Is there a more efficient way to do this in MongoDB, or is this a problem best suited for a RDBMS?
1. Which of the following relationship uses references to describe documents between connected data? Explanation: One-to-Many Relationships with document references presents a data model that uses references to describe one-to-many relationships between documents.
In fact, MongoDB allows relationships between documents to be modeled via Embedded and Referenced approaches.
In MongoDB, one-to-one, one-to-many, and many-to-many relations can be implemented in two ways: Using embedded documents. Using the reference of documents of another collection.
I asked Eliot Horowitz this very same question recently at MongoDB SV conference. He said the way he would structure it is to store each users friends as embedded documents within each user. For example, the structure might look like this:
{
_id : ObjectId("4e77bb3b8a3e000000004f7a"),
username : "alex",
friends : ["283956723823626626aa", "226567377578888888as", "8738783888aas88a8a88" ]
}
then you can have an index on user.friends
http://www.mongodb.org/display/DOCS/Indexes#Indexes-IndexingArrayElements
"When a document's stored value for a index key field is an array, MongoDB indexes each element of the array. See the Multikeys page for more information."
so to find all of "alex"'s friends I can just do:
db.user.find( { 'friends' : '4e77bb3b8a3e000000004f7a'});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With