我有一份文件,其结构如下(简化):
{
"containers": [
{
"containerId": 1,
"components": ["component1", "component2"]
},
{
"containerId": 2,
"components": ["component3", "component1"]
}]
}
如何编写从BOTH容器中删除“component1”的查询?这可能吗?
到目前为止,我已尝试使用{"$pullAll": { "containers.$.component": ["component1"]}}
$pull
进行类似查询,设置multi: true
,但我总是最终从第一个数组中删除该组件(我正在使用.update()
)
编辑:未来的原始数据!
{
"_id" : ObjectId("53a056cebe56154c99dc950b"),
"_embedded" : {
"click" : {
"items" : [],
"_links" : {
"self" : {
"href" : "http://localhost/v1/click"
}
}
},
"container" : {
"_links" : {
"self" : {
"href" : "http://localhost/v1/container"
}
},
"items" : [
{
"name" : "Container test",
"uriName" : "Container_test",
"description" : "this is a test container",
"containerId" : "CONTAINER TEST+SITE_TEST",
"component" : [
"ANOTHER COMPONENT+SITE_TEST",
"ANOTHER COMPONENT+SITE_TEST",
"SARASA+SITE_TEST"
],
"_links" : {
"self" : {
"href" : "http://localhost/v1/container/CONTAINER TEST+SITE_TEST"
}
}
},
{
"name" : "sasasa",
"uriName" : "sasasa",
"description" : "container description",
"containerId" : "SASASA+SITE_TEST",
"component" : [
"ANOTHER COMPONENT+SITE_TEST",
"COMPONENT+SITE_TEST",
"FAFAFA+SITE_TEST",
"SARASA+SITE_TEST"
],
"_links" : {
"self" : {
"href" : "/v1/container/SASASA+SITE_TEST"
}
}
}
]
}
},
"name" : "SITE_TEST",
"siteId" : "SITE_TEST",
"url" : "/v1/site"
}
好的,我正在尝试从两个容器中删除组件“SARASA + SITE_TEST”。我正在使用robomongo来测试查询。我已经尝试了db.site.update({"_embedded.container.items.component": "SARASA+SITE_TEST"},{"$pullAll": { "_embedded.container.items.component": ["SARASA+SITE_TEST"]}}, {multi: true})
但它没有用,之前我已经尝试了db.site.update({"_embedded.container.items.component": "SARASA+SITE_TEST"},{"$pull": { "_embedded.container.items.$.component": "SARASA+SITE_TEST"}}, {"multi": true})
,但它也没有用。我假设robomongo直接暴露了mongo驱动程序,我没有尝试从命令行运行它。
(该文档是“站点”,这就是为什么我的查询以db.site开头)
答案 0 :(得分:0)
我遇到了类似的问题,我尝试了$ pullAll并且有效。
https://docs.mongodb.org/manual/reference/operator/update/pullAll/
答案 1 :(得分:-1)
我尝试了数据的简化版本和$ pull工作:
> db.testcoll.insert({"containers": {"containreId": 1, "components": ["component1", "component2"]}})
> db.testcoll.insert({"containers": {"containreId": 2, "components": ["component3", "component1"]}})
> db.testcoll.find()
{ "_id" : ObjectId("53a8428ca2696f063b5c51eb"), "containers" : { "containreId" : 1, "components" : [ "component1", "component2" ] } }
{ "_id" : ObjectId("53a8429ea2696f063b5c51ec"), "containers" : { "containreId" : 2, "components" : [ "component3", "component1" ] } }
> db.testcoll.update({"containers.components": "component1"}, {$pull: {"containers.components": "component1"}}, {multi: true})
> db.testcoll.find()
{ "_id" : ObjectId("53a8428ca2696f063b5c51eb"), "containers" : { "components" : [ "component2" ], "containreId" : 1 } }
{ "_id" : ObjectId("53a8429ea2696f063b5c51ec"), "containers" : { "components" : [ "component3" ], "containreId" : 2 } }