簡體   English   中英

根據動態定義數組的元素位置刪除mongoDB數組中的元素

[英]Removing an element in a mongoDB array based on the position of element with dynamically defined array

我的問題是:

本題: 根據元素的位置刪除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 作為驅動程序

在 Mongo 版本 4.2+ 上,您可以使用管道更新來實現這一點,您可以通過多種方式完成它,這是我認為最簡單的兩種方式:

  1. 使用$slice$concatArrays刪除某個元素:
db.collection.update({},
[
  {
    $set: {
      [arrayName]: {
        $concatArrays: [
          {
            $slice: [
              `$${arrayName}`,
              index,
            ]
          },
          {
            $slice: [
              `$${arrayName}`,
              index + 1,
              {
                $size: `$${arrayName}`
              }
            ]
          }
        ]
      }
    }
  }
])

蒙戈游樂場

  1. 使用$filter$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
            ]
          }
        }
      }
    }
  }
])

或者你可以只准備

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM