这是你的答案:MongoDB pull array element from a collection
要从某个文档的数组中删除特定元素,首先您需要识别该元素。例如,我有一个包含数组的文档,并且该数组的每个元素都是一个对象:
{
"_id" : ObjectId("5140f34888dd50971900002d"),
"_permissions" : {
"edit" : [
{
"profile_id" : NumberLong(123),
"comment" : "app/project owner"
},
{
"profile_id" : NumberLong("153579099841888257"),
"comment" : "project admin"
},
{
"profile_id" : NumberLong("153579095869882369"),
"comment" : "project admin"
}
],
"view" : [
{
"profile_id" : NumberLong(123),
"comment" : "app/project owner"
},
{
"profile_id" : NumberLong("153579099841888257"),
"comment" : "project admin"
},
{
"profile_id" : NumberLong("153579095869882369"),
"comment" : "project admin"
}
]
}
}
所以让我们从_permissions.view 数组中删除带有“153579099841888257”值的profile_id。
来了
db.collection.update({_id: ObjectId("5140f34888dd50971900002d")}, {$pull:{"_permissions.view": {"profile_id": NumberLong("153579099841888257")}}});
- 我定义了对象的范围(以确保 id 不会影响任何其他首次找到的文档)
- 确定需要提取的元素:
profile_id,_permissions.view 数组中的值为“153579099841888257”