1

I have a document like this:

{
   _id : ObjectID(),
   title: "",
   items: [
      {
         "itemId" : 1234678,
      }
   ]
}

itemId is a unique index created like this:

db.allItems.createIndex( { "items.itemId" : 1 }, { unique: true});

And then everything works fine, until I set items array (not pushing one), in this case, unique index does not work. The following data in the update operation (using $set) does not throw an error and works fine, which MUST NOT. I mean it creates the sub-document without any unique error

items: [
  {
    itemId: 1234678
  },
  {
    itemId: 1234678
  }
]

While I expect MongoDB to throw error that itemId is not unique.

1 Answer 1

1

MongoDb index uniqueness is applicable for documents, not for nested arrays.

If you try to insert new document with:

items: [
  {
     "itemId" : 1234678,
  },
  ...
]

MonogDB will throw E11000 duplicate key error collection

Sign up to request clarification or add additional context in comments.

2 Comments

is it related to $set or it generally ignores it?
@MostafaTalebi it generally ignores

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.