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!
To create a unique index, use the db. collection. createIndex() method with the unique option set to true .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With