Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - unique multikey index not working as expected

I have a problem with multikey indexes in MongoDB.

I have a collection named users, whose documents look more or less like this:

{
  "_id": ObjectId(),
  "name": "John Smith",
  ...
  "votes": [
    {
      "type": "news",
      "votedObjectId": "123"
    },
    {
      "type": "blog",
      "votedObjectId": "124"
    },
    {
      "type": "news"
      "votedObjectId": "225"
    }
  ]
}

I want to create an index on votedObjectId and I want users to vote only once for each article.

I ensured a unique index (code is in node.js - mongoskin module):

`this.ensureIndex({'votes.votedObjectId': 1}, {unique: true}, ...)`

Then I tried voting twice for the same article, and it actually added the exact same vote twice.

How can I ensure that the array will not contain duplicate elements?

P.S.

I do all inserts with {safe: true}, and the duplicate values I get are not returned by an insert operation, but actually inserted in the collection.

like image 449
lortabac Avatar asked Dec 12 '22 20:12

lortabac


1 Answers

The {unique: true} only guarantees uniqueness across objects, it does NOT guarantee uniqueness of the array elements inside the array.

But check out the addToSet functionality of mongodb.

Also this very similar question here. How to ensure unique item in an array based on specific fields - mongoDB?

like image 110
VladT Avatar answered Dec 29 '22 01:12

VladT