gpt4 book ai didi

node.js - 如何在 MONGODB 的嵌套文档数组中 $pull 文档

转载 作者:可可西里 更新时间:2023-11-01 10:13:31 29 4
gpt4 key购买 nike

How to remove data from documents which have userId = "fadd66e5-97b9-4ae0-86ca-7922bf9d1da4" in parentHierarchy and have 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"
}
]
}
]
}]

Output Document should be come in this format(which have no parenthierarchy in this organisationId "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"
}
]
}
]
}]

I have used query like this but not return proper data.

  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");

}
})

最佳答案

Pull 运算符通过应用查询来工作,因为它是顶级文档,所以当条件找到文档时,它会删除 organization 嵌入数组中的文档。

您必须使用位置运算符来删除 parentHierarchy 嵌入式数组中的文档。

查询条件定位 organization 元素,后跟 $pull 以删除 parentHierarchy 文档数组中与 userid 匹配的所有文档。

var condition={"organization.organizationId":condition.orgId}
var update={"organization.$.parentHierarchy":{"userId": userdata[0]._id}}

关于node.js - 如何在 MONGODB 的嵌套文档数组中 $pull 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47907453/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com