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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With