title: How to add a unique index on an embedded array in Mongo DB collection
body: <p>I am trying to create unique index on scorecardList.filename field in below mentioned mongo collection. The purpose is we should not be able to create another element in scorecardList with same filename.</p>
  
  <p>Mongo Schema: </p>
  
  <pre><code>{
      "Name": "Ravikant Khond",
      "PIN" : "411057",
      "scorecardList": [
          {
              "fileName" : "ScoreCard_April_2016.pdf",
              "runDate" : ISODate("2016-05-01T00:00:00.000Z"),
              "month" : "April",
              "year" : "2016"
          },
          {
              "fileName" : "ScoreCard_May_2016.pdf",
              "runDate" : ISODate("2016-06-01T00:00:00.000Z"),
              "month" : "May",
              "year" : "2016"
          }
      ]
  }
  </code></pre>
  
  <p>[1]</p>
  
  <p>Mongo command I tried to use while creating unique index is as follows:</p>
  
  <pre><code>db.testing.createIndex(
      { "scorecardList.filename": 1 },
      { 
          unique: true, 
          partialFilterExpression: { 
              "scorecardList.filename": { $exists: true } 
          } 
      }
  );
  </code></pre>
  
  <p>Even though the index has been created I am able to add a scorecard with existing filename.</p>
  
  <p>Please help.</p>