title: MongoDB Unique index on multiple field
body: <p>I'm using a MongoDb database and I need to make multiple fields unique. What I need is for MongoDb to check if the <em>combination</em> of the multiple fields are unique. Let's show an example of what I need:</p>
  
  <p>If I add the following in this order in the database after adding the indexes: <br>
  <code>{"name":"paul", "age":"21"}</code><br>
  <code>{"name":"goerge", "age":"21"}</code><br>
  <code>{"name":"paul", "age":"44"}</code><br>
  <code>{"name":"paul", "age":"21"}</code></p>
  
  <p>In the following example, the <em>only</em> one who would <em>not</em> be accepted would be the last one.</p>
  
  <p>I've tried the following unique compound index and <strong>it doesn't work. In the preceding example, it would only keep the first one as it checks if every field is unique</strong>:</p>
  
  <p><code>db.test.createIndex({"name":1, "age":1}, {unique:true})</code></p>
  
  <p>I also tried, same problem:</p>
  
  <p><code>db.test.createIndex({"name":1}, {unique:true})</code><br>
  <code>db.test.createIndex({"age":1}, {unique:true})</code></p>
  
  <p>I searched for hours and couldn't find anything that would enable me to do that.</p>
  
  <p>Anyone knows a way?</p>