문제

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.

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top