Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
向MongoDB的嵌入文档中的数组类型字段添加唯一索引_Mongodb_Indexing - Fatal编程技术网

向MongoDB的嵌入文档中的数组类型字段添加唯一索引

向MongoDB的嵌入文档中的数组类型字段添加唯一索引,mongodb,indexing,Mongodb,Indexing,首先,将唯一索引添加到字段“items.barcode” db.clothes.createIndex({'items.barcode': 1}, {unique: 1}); 然后,在表中插入一些文档 db.clothes1.remove({}); db.clothes.insert([ { // success _id: '1', items: [ {barcode: ['122', '122']}, {

首先,将唯一索引添加到字段
“items.barcode”

db.clothes.createIndex({'items.barcode': 1}, {unique: 1});
然后,在
表中插入一些文档

db.clothes1.remove({});
db.clothes.insert([
    { // success
        _id: '1',
        items: [
            {barcode: ['122', '122']},
            {barcode: ['122', '124']}
        ]
    },
    { // success
        _id: '2',
        items: [
            {barcode: ['222', '223']},
            {barcode: ['224', '225']}
        ]
    },
    { // failed
        _id: '3',
        items: [
            {barcode: ['122', '323']},
            {barcode: ['324', '325']}
        ]
    }
]);
现在我们可以看到第三个文档插入失败,导致错误:

'E11000重复密钥错误索引:duolayimeng.Closes1.$items.barcode_1重复密钥:{:“122”}'

但是在第一个文档的两个嵌入文档中,
'barcode'
字段有3个元素是
'122'



我对这种情况感到困惑。MongoDB如何决定嵌入文档中的数组类型字段(如
'items.barcode'
)是否唯一?

这是因为索引在文档的集合中是唯一的

子文档不是真正的文档,文档必须具有唯一字段,子文档不能在文档内部强制唯一

id为3的文档失败,因为已存在具有相同唯一密钥的其他文档

id为1的文档正在插入“确定”,因为没有其他文档具有相同的唯一字段

当您想要在文档中实现唯一性时,必须在客户端实现该唯一性,或者修改模式,并使用

唯一索引允许将以下文档插入到 如果集合中没有其他文档具有a.b 5的值:

这是你的电话号码

db.collection.insert( { a: [ { b: 5 }, { b: 5 } ] } )