title: Custom MongoDB Object _id vs Compound index
body: <p>So I need to create a lookup collection in MongoDB to verify uniqueness. The requirement is to check if the same 2 values are being repeated or not. In SQL, I would something like this</p>
  
  <pre><code>SELECT count(id) WHERE key1 = 'value1' AND key2 = 'value2'
  </code></pre>
  
  <p>If the above query returns a count then it means the combination is not unique. I have 2 solutions in mind but I am not sure which one is more scalable. There are 30M+ docs against which I need to create this mapping.</p>
  
  <p><strong>Solution1:</strong></p>
  
  <p>I create a collection of docs with compound index on key1 and key2</p>
  
  <pre><code>{
    _id: &lt;MongoID&gt;,
    key1: &lt;value1&gt;,
    key2: &lt;value2&gt;
  }
  </code></pre>
  
  <p><strong>Solution2:</strong></p>
  
  <p>I write application logic to create custom _id by concatenating value1 and value2</p>
  
  <pre><code>{
    _id: &lt;value1&gt;_&lt;value2&gt;
  }
  </code></pre>
  
  <p>Personally, I feel the second one is more optimised as it only has a single index and the size of doc is also smaller. But I am not sure if it is a good practice to create my own _id indexes as they may not be completely random. What do you think?</p>
  
  <p>Thanks in advance.</p>
  
  <p><strong>Update:</strong></p>
  
  <p>My database already has a lot of indexes which take up memory so I want to keep index size to as low as possible specially for collections which are only used to verify uniqueness.</p>