简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM