title: How to efficiently count one-to-squillion relationships in Mongoose / MongoDB? (e.g. the "like" count for a Tweet on Twitter)
body: <p>Let's imagine I'm building an app similar to Twitter just for an easy example (and using Mongoose / MongoDB).</p>
  
  <p>I'd have a collection for "tweets" and my question is: <strong>how can I manage the "like count" for a tweet without putting unnecessary strain on the database?</strong></p>
  
  <p>My first instinct was to have another collection named "likes" and each document would store the id of the user who liked the tweet, and the id of the tweet they liked.</p>
  
  <p>But then I realized if I want show 20 tweets on the front-end it would take me 21 queries (<strong>this is where I think I'm misunderstanding something basic and it shouldn't take me this many queries</strong>). One query to find the 20 most recent tweets, and another query-per tweet to count how many related "like" documents there are for it. Is there a more efficient way of handling that in MongoDB? Or is this where I'd need to turn to some sort of caching solution in my app?</p>
  
  <p>My next thought was to instead embed a "usersWhoHaveLiked" array within each tweet document like this:</p>
  
  <pre><code>{
      _id: ObjectId("abc123abc123"),
      title: "My first tweet",
      author: 3,
      usersWhoHaveLiked: [3, 20, 17, 5]
  }
  </code></pre>
  
  <p>But if hundreds of thousands of users can "like" a tweet that array could become incredibly large and I'm worried that modifying an array of that size could be CPU-expensive / slow, or outright overflow the 16mb per document allowed.</p>
  
  <p>I realize there are <em>many</em> different ways of architecting this solution, so I'm not looking for a <strong>best</strong> way, which I know would be highly subjective... what makes this quesiton atleast a little bit objective is that we want to minimize stress put on the db &amp; server; which <strong>is</strong> measurable.</p>
  
  <p>I'm a database rookie so if there's a Mongoose / MongoDB flavored way of handling this please feel free to point out things that might be painfully obvious to others :)</p>
  
  <p>Thanks!</p>