1

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.

Community
  • 1
  • 1
kir
  • 581
  • 1
  • 6
  • 22
  • Perhaps this page of the docs will help - http://docs.mongodb.org/manual/core/index-multikey/ – Lix Apr 08 '14 at 10:43
  • I tried `db.songs.ensureIndex({listeners:1},{unique:true})` and it just prevented me from making new songs that has the same listeners. I may be using it wrong though. – kir Apr 08 '14 at 10:45
  • A unique index will not work! It is collection wide and that is probably why you are gettting an error, drop that index and use $addToSet instead – Sammaye Apr 08 '14 at 11:03

1 Answers1

1
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.

Sammaye
  • 43,242
  • 7
  • 104
  • 146
  • I'm sorry for a late question, but whenever I use addToSet I never get any errors even when nothing is added (aka the same element is already inside the field). How do I know if the add is successful or not? I'm using Mongoose with NodeJS. – kir Apr 10 '14 at 03:47
  • @kir yeah addtoset doesn't currently tell you if it is duplicate, you can use query magic to solve that, basically add to your find() something like `listeners:{$ne:'John'}` But there is a JIRA somewhere to throw failure when addtoset can't add – Sammaye Apr 10 '14 at 06:57
  • 1
    @kir ok it seems in 2.6 this has been fixed: https://jira.mongodb.org/browse/SERVER-2769 try and upgrade – Sammaye Apr 10 '14 at 06:57