3

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?

3
  • 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 Commented Oct 20, 2015 at 1:54
  • Edited the post. In the example, the index are already set and we add those new documents. Commented Oct 21, 2015 at 4: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. Commented Oct 21, 2015 at 5:07

2 Answers 2

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})
Sign up to request clarification or add additional context in comments.

Comments

0

In my case I had used capitals for the first letter of the names of the fields but small letters when creating the index, so data was like

{"Name":"Paul", "Age":"21"} 

but index was set like

key: { name: 1, age: 1 }

instead of

key: { Name: 1, Age: 1 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.