title: How to ensure unique item in an array based on specific fields - mongoDB?
body: <p>In my scenerio, there are authors in a collection, each author has <code>messages</code> and each message of author can has <code>events</code>. Each actor allowed to perform only one kind of action once. </p>
  
  <pre><code>db.people.ensureIndex({messages.messageEvents.eventName: 1, messages.messageEvents.actorId: 1}, {unique: true});
  </code></pre>
  
  <p>I added index but it has no effect. As you see below, my document has three elements which have <code>"eventName":"vote"</code> and <code>"actorId":"1234"</code> that should be against my constraint.</p>
  
  <p>How to ensure unique item in <code>messageEvents</code> array based on <code>eventName</code> and <code>actorId</code> fields ?</p>
  
  <p>Actually, i need to update the existing item without a second search and update event instead of rejecting it .</p>
  
  <pre><code>{
    "_id": "1234567",
    "authorPoint": 0,
    "messages": [
      {
        "messageId": "112",
        "messageType": "Q",
        "messagePoint": 0,
        "messageEvents": [
          {
            "eventName": "Add",
            "actorId": "1234",
            "detail": ""
          },
          {
            "eventName": "Vote",
            "actorId": "1234",
            "detail": "up"
          },
          {
            "eventName": "Vote",
            "actorId": "1234",
            "detail": "down"
          },
          {
            "eventName": "Vote",
            "actorId": "1234",
            "detail": "cork"
          }
        ]
      }
    ]
  }
  </code></pre>