MongoDB 中的 $pull 运算符
$pull operator in MongoDB
{
"_id" : ObjectId("5badfada90fd543fd8aa7f96"),
"__v" : 0,
"deleted" : false,
"groups" : [
{
"group" : "grp",
"_id" : ObjectId("5bae09a601123357e58b66a2"),
"activities" : [
ObjectId("5bae09a601123357e58b66a3"),
ObjectId("5bae10de01123357e58b66a6")
]
},
{
"group" : "123",
"_id" : ObjectId("5bae0f1001123357e58b66a4"),
"activities" : [
ObjectId("5bae0f1001123357e58b66a5")
]
}
],
"nextActivityId" : 22,
"name" : "test",
"year" : "1",
"status" : "2",
"vision" : ObjectId("5bab2f4872acf42a81c124d0")
}
以上架构是 "Plan" 架构
我必须编写一个查询来删除 "activities" 数组中的 Activity。对此的最佳解决方案是什么?我将如何使用 $pull 来实现这一目标
这是我的解决方案,但它会删除完整的组数组
Plan.update({ _id: PLAN ID }, { $pull: { groups: { activities: ACTIVITY ID } } })
计划 ID 为:“_id”:ObjectId(“5badfada90fd543fd8aa7f96”),
ACTIVITY ID 例如:ObjectId("5bae09a601123357e58b66a3")
谢谢!
您需要使用位置 $
更新运算符。
db.Plan.update(
{ "_id" : PLAN ID },
{ "$pull": { "groups.$.activities": ACTIVITY ID } }
)
你可以试试这个,
db.Plan.update({ _id: ObjectId("5badfada90fd543fd8aa7f96"),"groups.activities":{$in:[ ObjectId("5bae09a601123357e58b66a3") ]}},
{ $pull: { "groups.$.activities": ObjectId("5bae09a601123357e58b66a3") } });
位置运算符在使用 $
仅更新对象时未从查询警告中找到所需的匹配项。
{
"_id" : ObjectId("5badfada90fd543fd8aa7f96"),
"__v" : 0,
"deleted" : false,
"groups" : [
{
"group" : "grp",
"_id" : ObjectId("5bae09a601123357e58b66a2"),
"activities" : [
ObjectId("5bae09a601123357e58b66a3"),
ObjectId("5bae10de01123357e58b66a6")
]
},
{
"group" : "123",
"_id" : ObjectId("5bae0f1001123357e58b66a4"),
"activities" : [
ObjectId("5bae0f1001123357e58b66a5")
]
}
],
"nextActivityId" : 22,
"name" : "test",
"year" : "1",
"status" : "2",
"vision" : ObjectId("5bab2f4872acf42a81c124d0")
}
以上架构是 "Plan" 架构 我必须编写一个查询来删除 "activities" 数组中的 Activity。对此的最佳解决方案是什么?我将如何使用 $pull 来实现这一目标 这是我的解决方案,但它会删除完整的组数组
Plan.update({ _id: PLAN ID }, { $pull: { groups: { activities: ACTIVITY ID } } })
计划 ID 为:“_id”:ObjectId(“5badfada90fd543fd8aa7f96”), ACTIVITY ID 例如:ObjectId("5bae09a601123357e58b66a3")
谢谢!
您需要使用位置 $
更新运算符。
db.Plan.update(
{ "_id" : PLAN ID },
{ "$pull": { "groups.$.activities": ACTIVITY ID } }
)
你可以试试这个,
db.Plan.update({ _id: ObjectId("5badfada90fd543fd8aa7f96"),"groups.activities":{$in:[ ObjectId("5bae09a601123357e58b66a3") ]}},
{ $pull: { "groups.$.activities": ObjectId("5bae09a601123357e58b66a3") } });
位置运算符在使用 $
仅更新对象时未从查询警告中找到所需的匹配项。