如何从parentHierarchy中具有userId =“fadd66e5-97b9-4ae0-86ca-7922bf9d1da4”的文档中删除数据,并使organizationId =“d44a90c0-3f04-4dbd-97f0-cd1be3baf2de”。
这是文件。
[ {
"name": "ABC",
"organization": [
{
"organizationId": "d44a90c0-3f04-4dbd-97f0-cd1be3baf2de",
"parentHierarchy": [
{
"privelege": "Admin",
"userId": "fadd66e5-97b9-4ae0-86ca-7922bf9d1da4"
},
{
"privelege": "Manager",
"userId": "fadd56e5-97b9-4ae0-86ca-7922bf9d1da4"
}
]
},
{
"organizationId": "d44a90c1-3f04-4dbd-97f0-cd1be3baf2de",
"parentHierarchy": [
{
"privelege": "Admin",
"userId": "fada66e5-97b9-4ae0-86ca-7922bf9d1da4"
},
{
"privelege": "Manager",
"userId": "fndd56e5-97b9-4ae0-86ca-7922bf9d1da4"
}
]
}
]
},
{
"name": "PQR",
"organization": [
{
"organizationId": "d44a90c0-3f04-4dbd-97f0-cd1be3baf2de",
"parentHierarchy": [
{
"privelege": "Admin",
"userId": "fadd66e5-97b9-4ae0-86ca-7922bf9d1da4"
},
{
"privelege": "Manager",
"userId": "fadd56e5-97b9-4ae0-86ca-7922bf9d1da4"
}
]
}
]
}]
输出文档应该采用这种格式(在此组织中没有父级层次结构“d44a90c0-3f04-4dbd-97f0-cd1be3baf2de”)。
[ {
"name": "ABC",
"organization": [
{
"organizationId": "d44a90c0-3f04-4dbd-97f0-cd1be3baf2de",
"parentHierarchy": [
{
"privelege": "Manager",
"userId": "fadd56e5-97b9-4ae0-86ca-7922bf9d1da4"
}
]
},
{
"organizationId": "d44a90c1-3f04-4dbd-97f0-cd1be3baf2de",
"parentHierarchy": [
{
"privelege": "Admin",
"userId": "fada66e5-97b9-4ae0-86ca-7922bf9d1da4"
},
{
"privelege": "Manager",
"userId": "fndd56e5-97b9-4ae0-86ca-7922bf9d1da4"
}
]
}
]
},
{
"name": "PQR",
"organization": [
{
"organizationId": "d44a90c0-3f04-4dbd-97f0-cd1be3baf2de",
"parentHierarchy": [
{
"privelege": "Manager",
"userId": "fadd56e5-97b9-4ae0-86ca-7922bf9d1da4"
}
]
}
]
}]
我使用了这样的查询但没有返回正确的数据。
var condition = {"organization.organizationId":condition.orgId,
"organization.parentHierarchy.userId": userdata[0]._id}
var update = {
"$pull":{"organization":
{"organizationId": condition.orgId,
"parentHierarchy":{"userId": userdata[0]._id}}}
}
db.collection('users').update(condition, update, {multi: true},
function(error, documents) {
if(error){
console.log("error in to update parentHierarchy");
}
else{
console.log("updated Documents");
}
})
答案 0 :(得分:2)
拉取算子通过应用查询来工作,因为它是顶级文档,因此当条件找到文档时,它会删除organization
嵌入数组中的文档。
您必须使用位置运算符删除parentHierarchy
嵌入数组中的文档。
查询条件查找organization
元素后跟$pull
,以删除与parentHierarchy
文档数组中的userid匹配的所有文档。
var condition={"organization.organizationId":condition.orgId}
var update={"organization.$.parentHierarchy":{"userId": userdata[0]._id}}