我的問題是:
本題:根據元素的位置洗掉mongoDB中的陣列元素
還有這個問題:mongodb set object where key value dynamic changes
我知道您可以像這樣動態定義欄位(陣列):
{ [arrayName]: { <condition> } }
但是,然后我想通過指定位置(這也是動態定義的)來洗掉動態定義的陣列中的某個元素。換句話說,處理這個查詢的函式傳入了兩個引數:陣列的名稱和要洗掉的元素的索引。
所選答案給出的選項如下:
選項 1不起作用(通常),適合我的情況,如下所示:
{ $pull : { [arrayName] : { $gt: index-1, $lt: index 1 } } }
選項 2,我不能在帶引號的欄位選擇器中使用動態定義的值(據我所知):
{ $pull : "[arrayName].[index]" }
或者
{ $pull : "[arrayName].$": index }
選項 3是不同的方法,但出于相同的原因不能使用它:
{ $unset: { "[arrayName].[index]": 1 } } // Won't work
{ $pull: { [arrayName]: null } } // Would probably work
我現在能想到的唯一解決方法是顯著改變設計,這將是一種恥辱。任何幫助表示贊賞!
PS:我在今天的最新版本(v6.3.5)和 MongoDB 版本 5.0.8 上使用 mongoose 作為驅動程式
uj5u.com熱心網友回復:
在 Mongo 版本 4.2 上,您可以使用管道更新來實作這一點,您可以通過多種方式完成它,這是我認為最簡單的兩種方式:
- 使用
$sliceand$concatArrays洗掉某個元素:
db.collection.update({},
[
{
$set: {
[arrayName]: {
$concatArrays: [
{
$slice: [
`$${arrayName}`,
index,
]
},
{
$slice: [
`$${arrayName}`,
index 1,
{
$size: `$${arrayName}`
}
]
}
]
}
}
}
])
蒙戈游樂場
- 使用
$filterand$zip根據索引過濾掉:
db.collection.updateOne(
{},
[
{
"$set": {
[arrayName]: {
$map: {
input: {
$filter: {
input: {
$zip: {
inputs: [
{
$range: [
0,
{
$size: `$${arrayName}`
}
]
},
`$${arrayName}`
]
}
},
cond: {
$ne: [
{
"$arrayElemAt": [
"$$this",
0
]
},
index
]
}
}
},
in: {
$arrayElemAt: [
"$$this",
1
]
}
}
}
}
}
])
或者你可以只準備
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487237.html
