从文档中得知:
{ $pull : { field : {$gt: 3} } } removes array elements greater than 3
所以我认为目前你可以做类似于这样的事情:
{ $pull : { field : {$gt: 3, $lt: 5} } } // shoud remove elemet in 4 position
或者尝试使用定位运算符进行更新,我认为应该像这样:
{ $pull : "field.4" }
{ $pull : {"field.$": 4}}
这仅是一个建议,因为我现在无法测试它。
更新:
看起来你现在不能一步完成它(jira中有此错误)
但是你可以先删除指定位置的元素,然后再拉取值为null的元素:
{$unset : {"array.4" : 1 }}
{$pull : {"array" : null}}
_id: ObjectId("5e4539cb6aebbeaa0a6b8fe7")
}, [
{ $set:
{ notes:
{
$concatArrays: [
{ $slice: ['$notes', 4] },
{ $slice: ['$notes', { $add: [1, 4] }, { $size: '$notes' }]}
]
}
}
}
])```
以下是您的答案:如何从MongoDB集合中提取数组元素
要从某个文档的数组中删除特定元素,首先需要确定该元素。例如,我有一个带有数组的文档,该数组的每个元素都是一个对象:
{
"_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")}}});
_permissions.view
数组中值为 "153579099841888257" 的 profile_id