[英]Removing an element in a mongoDB array based on the position of element with dynamically defined array
[英]Removing the array element in mongoDB based on the position of element
從文檔:
{ $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}}
這只是一個建議,因為我現在無法測試它。
更新:
但是您可以使用 unset element in position 刪除並使用空值拉動元素:
{$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 從集合中提取數組元素
要首先從某個文檔的數組中刪除特定元素,您需要識別此元素。 例如,我有一個帶有數組的文檔,該數組的每個元素都是一個對象:
{
"_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")}}});
profile_id
與在“153579099841888257”值_permissions.view
陣列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.