Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Unique Key in Embedded Document

Tags:

Is it possible to set a unique key for a key in an embedded document?

I have a Users collection with the following sample documents:

 {        Name: "Bob",        Items: [            {                Name: "Milk"            },            {                Name: "Bread"            }        ]     },     {        Name: "Jim"     }, 

Is there a way to create an index on the property Items.Name?

I got the following error when I tried to create an index:

> db.Users.ensureIndex({"Items.Name": 1}, {unique:true}); E11000 duplicate key error index: GroceryGuruApp.Users.$Items.Name_1  dup key: {  : null } 

Any suggestions? Thank you!

like image 563
Abe Avatar asked Dec 14 '10 03:12

Abe


People also ask

How do I make a key unique in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

What is unique key in MongoDB?

Unique Constraint in MongoDB will allow only a single document with the same value for the indexed key. If we attempt to insert the same value for a single indexed key, it will result in an error. This returns every document in the collection. This is an attempt to insert a record with the same code.

How does MongoDB store unique values?

To get unique values and ignore duplicates, use distinct() in MongoDB. The distinct() finds the distinct values for a specified field across a single collection and returns the results in an array.

Does MongoDB support unique indexes?

Restrictions. MongoDB cannot create a unique index on the specified index field(s) if the collection already contains data that would violate the unique constraint for the index. You may not specify a unique constraint on a hashed index.


1 Answers

Unique indexes exist only across collection. To enforce uniqueness and other constraints across document you must do it in client code. (Probably virtual collections would allow that, you could vote for it.)

What are you trying to do in your case is to create index on key Items.Name which doesn't exist in any of the documents (it doesn't refer to embedded documents inside array Items), thus it's null and violates unique constraint across collection.

like image 195
pingw33n Avatar answered Sep 28 '22 04:09

pingw33n