2

I'm using a MongoDb database and I need to make multiple fields unique. What I need is for MongoDb to check if the combination of the multiple fields are unique. Let's show an example of what I need:

If I add the following in this order in the database after adding the indexes:
{"name":"paul", "age":"21"}
{"name":"goerge", "age":"21"}
{"name":"paul", "age":"44"}
{"name":"paul", "age":"21"}

In the following example, the only one who would not be accepted would be the last one.

I've tried the following unique compound index and it doesn't work. In the preceding example, it would only keep the first one as it checks if every field is unique:

db.test.createIndex({"name":1, "age":1}, {unique:true})

I also tried, same problem:

db.test.createIndex({"name":1}, {unique:true})
db.test.createIndex({"age":1}, {unique:true})

I searched for hours and couldn't find anything that would enable me to do that.

Anyone knows a way?

CyanBalloon
  • 21
  • 1
  • 4
  • 1
    It sounds like you already have duplicate data, and also that various index attempts will not be helping. You should drop all indexes before creating with your first attempt and remove all duplicates first. See [remove dups from mongodb](http://stackoverflow.com/questions/31557053/remove-dups-from-mongodb/31558107#31558107) – Blakes Seven Oct 20 '15 at 01:54
  • Edited the post. In the example, the index are already set and we **add** those new documents. – CyanBalloon Oct 21 '15 at 04:10
  • Cannot reproduce. With an indexed defined with `{"name":1, "age":1}, {unique:true}` then the last document insertion fails as it should. As suggested, it is supected that your collection already contains duplicate data and a procedure for removal is given. If just a test, then drop the collection and start again. – Blakes Seven Oct 21 '15 at 05:07

1 Answers1

2

You aren't able to create that index unique because you 've got the name & age not unique! Check Paul 21 years olds If you fix that value. The best way to create the index is this one

db.test.createIndex({"name":1, "age":1}, {unique:true})
Omkar Kulkarni
  • 1,091
  • 10
  • 22
Diego
  • 126
  • 1
  • 4