Mostafa Talebi
Mostafa Talebi

Reputation: 9183

MongoDB Unique Index issue in array of subdocuments

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.

Upvotes: 1

Views: 343

Answers (1)

Valijon
Valijon

Reputation: 13103

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

Upvotes: 1

Related Questions