简体   繁体   中英

MongoDB - unique compound index on array of nested documents

I have a compound unique index

db.collection("sheets").createIndex(
    {
        'cells.x': 1,
        'cells.y': 1
    },
    { unique: true }
);

so I can have documents like this:

{
    _id: "xxx",
    name: "sheet 1",
    cells: [{x:0, y:1, sheet_id: "xxx"}, {x:1, y:1, sheet_id: "xxx"}]
}

but when I create 2 documents with empty 'cells' array field, I get this error:

(node:23492) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: test.sheets index: cells.x_1_cells.y_1_cells.sheet_id_1 dup key: { cells.x: null, cells.y: null, cells.sheet_id: null }

notice the:

dup key: { cells.x: null, cells.y: null, cells.sheet_id: null }

ofcourse I dont reallt have a { cells.x: null, cells.y: null, cells.sheet_id: null } in the array. it is empty...

if the 'cells' array in one document is not empty, I can create a seconed document with an empty 'cells'.

how can I solve this and have more than one empty 'cells' array?

You can create a Partial Index that will index only documents that match its query. In this case, match only documents that have a "cell.x" - effectively saying documents which have some elements.

  db.sheets.createIndex({ "cells.x": 1, "cells.y": 1 }, 
    { unique: true, partialFilterExpression: { "cells.x": { $exists: true } } })

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