簡體   English   中英

如何在 mongodb 中查找和更新多個陣列元素

[英]How to FInd and Update Multiple Array Elements in mongodb

> db.Dashboards.find({user:{$regex:"adams"}}).pretty();
{
    "_id" : ObjectId("123"),
    "user" : "adam.adams",
    "widgets" : [
        {
            "_id" : ObjectId("124"),
            "column" : 1,
            "configMap" : {
                "coleg" : "bas.baser,cer.ceras,tom.tomsa"
            },
        }
    ]
}

我有一個 Mongo 數據庫,它保留上面的記錄,不幸的是,我需要在“coleg”字段中找到所有具有“cer.ceras”的用戶,然后將其替換為“per.peras”

我嘗試

db.Dashboards.find({widgets:{"$elemMatch":{configMap:{"$elemMatch":{coleg:/.*ceras.*/}}}}}}).pretty();

但我沒有為我找到任何東西

這可能有點復雜。

過濾器

該條件應與$regex一起使用以查找文本的出現。

更新

需要使用聚合管道進行更新。

  1. $set - 設置widgets字段。

    1.1。 $map - 迭代widgets數組中的元素並返回一個新數組。

    1.1.1。 $mergeObjects - 將當前迭代文檔與1.1.1.1的結果合並。

    1.1.1.1。 帶有configMap數組的文檔。 使用$mergeObjects將當前迭代的configMap文檔與結果1.1.1.1.1合並。

    1.1.1.1.1。 帶有coleg字段的文檔。 使用$replaceAll將所有匹配的文本“cer.ceras”替換為“per.peras”。

更新選項

{ multi: true }旨在更新多個文檔。

db.collection.update({
  widgets: {
    $elemMatch: {
      "configMap.coleg": {
        $regex: "cer\\.ceras"
      }
    }
  }
},
[
  {
    $set: {
      widgets: {
        $map: {
          input: "$widgets",
          in: {
            $mergeObjects: [
              "$$this",
              {
                configMap: {
                  $mergeObjects: [
                    "$$this.configMap",
                    {
                      coleg: {
                        $replaceAll: {
                          input: "$$this.configMap.coleg",
                          find: "cer.ceras",
                          replacement: "per.peras"
                        }
                      }
                    }
                  ]
                }
              }
            ]
          }
        }
      }
    }
  }
],
{
  multi: true
})

演示@Mongo Playground

暫無
暫無

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

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