title: Modeling friend of friend relationships in MongoDB
body: <p>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:</p>
  
  <ul>
  <li>Pull all friend user IDs from user doc</li>
  <li>Pull all friend arrays from user docs of those friends (using an $in query across all friend IDs), combine application-side into one set, then combine that with first-level friend user IDs to get set of all friends and friends of friends</li>
  <li>Use that set to perform the final query (using $in) across all friends and friends of friends</li>
  </ul>
  
  <p>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?</p>