Question

First of all, I've read this thread already and it didn't really help me on this particular problem. I'm also new to MongoDB.

I have a document in my db.songs collection:

{
    "title" : "Ignorance"
    "artist" : "Paramore"
    "listeners" : ["John", "Bill", "Amber"]
}

I want enforce no duplicates on the users key, such that whenever I push "John" or an existing user, I get an error. Can I do this in mongo shell, and if so how can I configure my collection to employ this behavior?

Some example code that should give me a duplicate error (or some similar error):

db.songs.update({title:"Ignorance"}, {'$push':{listeners:"John"}})

Thank you in advance.

Was it helpful?

Solution

db.songs.ensureIndex({listeners:1},{unique:true})

Adding this index will not work. MongoDB will not ensure uniqueness within the subdocument using a unique index, instead it will do it collection wide. That is quite possibly why you are getting errors u8sing that.

Instead what you want to do is use something that will add the item to the "set" of items, that is where $addToSet ( http://docs.mongodb.org/manual/reference/operator/update/addToSet/ ) comes in.

Drop your index and use that operator and it should work.

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