【发布时间】:2017-03-27 18:57:47
【问题描述】:
假设我有以下文档。
[
{
"username": "admin",
"accessControl": [
{
"methods": ["GET", "PUT"],
"items": ["A", "B"]
}
{
"methods": ["GET", "PUT", "CREATE"],
"items": ["C"]
}
]
}, {
"username": "user_1",
"accessControl": [
{
"methods": ["GET", "PUT"],
"items": ["A"]
}
]
}, {
"username": "user_2"
}
]
我需要在文档中插入以下内容。
{
"accessControl": [{
"methods": ["GET", "PUT"],
"items": ["B"]
}]
}
插入的部分需要按照当前结构合并到文档中。因此如果accessControl 不存在,则需要使用插入的项目来创建它;
如果存在accessControl 数组并包含带有"methods": ["GET", "PUT"] 的对象,则需要将项目"B" 推入对象的"items" 数组中。
如果存在accessControl 数组但不包含"methods": ["GET", "PUT"] 的对象,则需要插入accessControl { "methods": ["GET", "PUT"], "items": ["B"] }
这样我以后就可以有下面的文档结构了。
[
{
"username": "admin",
"accessControl": [
{
"methods": ["GET", "PUT"],
"items": ["A", "B"] //nothing inserted here since "B" is already present
}, {
"methods": ["GET", "PUT", "CREATE"],
"items": ["C"]
}
]
}, {
"username": "user_1",
"accessControl": [
{
"methods": ["GET", "PUT"],
"items": ["A", "B"] //item "B" has inserted here
}
]
}, {
"username": "user_2",
"accessControl": [
{
"methods": ["GET", "PUT"],
"items": ["B"] // item "B" is inserted along with the whole "accessControl"
}
]
}
]
【问题讨论】:
-
是否可以选择更改数据库结构?如果 accesscontrol 数组的每个 item 有一个文档,并且该对象上允许使用一组方法,则这种更新可能会更容易。
-
我想我会走那条路。改变结构看起来很有帮助
标签: mongodb mongodb-query