Question

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.

Was it helpful?

Solution

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?

OTHER TIPS

Try

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

or process voting with

this.update( 
  { _id:... , 'votes.votedObjectId':{$ne:'...'} }, 
  { $push: { votes: '...' }}
)

Hopefully, theese statements might help you to sort it out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top