实际上我需要根据它的位置从数组中删除一个元素。使用 $pop 我们可以从顶部或底部删除元素(将其视为堆栈。顶部的第 0 个元素),如此处所述。
我们还可以使用 $pull 根据数组中元素的值从数组中删除元素,如此处所述。
但我需要根据位置从数组中删除元素。那么有什么办法可以做到这一点。
从文档:
{ $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}}
这就是如何使用最新的 mongodb v4.2 做到这一点,丑陋但有效
_id: ObjectId("5e4539cb6aebbeaa0a6b8fe7")
}, [
{ $set:
{ notes:
{
$concatArrays: [
{ $slice: ['$notes', 4] },
{ $slice: ['$notes', { $add: [1, 4] }, { $size: '$notes' }]}
]
}
}
}
])```
这是你的答案: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"
}
]
}
}
所以让我们从数组中删除profile_id
“153579099841888257”值。_permissions.view
开始了
db.collection.update({_id: ObjectId("5140f34888dd50971900002d")}, {$pull:{"_permissions.view": {"profile_id": NumberLong("153579099841888257")}}});
profile_id
中有“153579099841888257”值_permissions.view