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 允许不同组合的CompoundIndex_Mongodb_Nosql_Key_Unique - Fatal编程技术网

Mongodb 允许不同组合的CompoundIndex

Mongodb 允许不同组合的CompoundIndex,mongodb,nosql,key,unique,Mongodb,Nosql,Key,Unique,我试图在mongodb集合上实现一个唯一索引,其中列表中的子文档组合是唯一的 允许为: 以下权限是允许的,因为在另一个示例中还有resourceID,它不会损害唯一索引 { "permission_name": "read", "role_id": 1, "value": "ALLOW", "attributes": [{ &qu

我试图在mongodb集合上实现一个唯一索引,其中列表中的子文档组合是唯一的

允许为: 以下权限是允许的,因为在另一个示例中还有resourceID,它不会损害唯一索引

{
    "permission_name": "read",
    "role_id": 1,
    "value": "ALLOW",
    "attributes": [{
        "key": "folderID",
        "value": "1"
    }],
}
不允许是: 以下条目在数据库中是两次

{
    "permission_name": "read",
    "role_id": 1,
    "value": "ALLOW",
    "attributes": [{
        "key": "folderID",
        "value": "1"
    }],
}
但当我使用以下方法创建索引时:
db.permissions.createIndex({“permissions\u name”、“role\u id”、“attributes.key”、“attributes.value”}、{unique:true})
,则“Allowed”中的示例由于键重复而不可能出现。

当MongoDB为值数组编制索引时,它会在索引中为每个数组条目创建一个单独的键

对于示例中的第一个文档,键是(使用
|
表示字段边界):

对于第二个文档,索引中将添加两个键:

"read"|1|"folderID"|"1"
"read"|1|"resourceID"|"1"
在索引上设置
unique:true
,则不允许索引中存在重复键。由于这两个文档都将创建键
“read”| 1 |“folderID”| 1
,因此不允许同时插入这两个键

如果能够将数组作为单个实体进行索引,则仍然会有问题,因为数组和字段顺序都很重要,因此以下数组都会被视为不同的:

"attributes": [{"key": "folderID",
                "value": "1"},
               {"key": "resourceID",
                "value": "1"  }]
为了确保数组元素组合的唯一性,您需要添加一个字段,该字段包含从元素派生的值,并唯一标识一组特定的字段/值对

一种可能是存储已排序字段/值列表的哈希,但这将要求应用程序在每次数组更改时重新计算has,并且任何更新都必须在新数组的同时提交新哈希才能生效

"read"|1|"folderID"|"1"
"read"|1|"resourceID"|"1"
"attributes": [{"key": "folderID",
                "value": "1"},
               {"key": "resourceID",
                "value": "1"  }]
"attributes": [{"key": "resourceID",
                "value": "1"  },
               {"key": "folderID",
                "value": "1"}]
"attributes": [{"key": "folderID",
                "value": "1"},
               {"value": "1",
                "key": "resourceID"}]