【问题标题】:Mongo4.0 How to concatenate two existing fields into one in MongoMongo4.0 如何在Mongo中将两个现有字段连接成一个
【发布时间】:2021-12-29 16:12:46
【问题描述】:

我一定要用Mongo4.0。

我有一个嵌套对象。

{
_id:1,
route:'abc',
children:[
{
   _id:2,
   parentRoute:'abc',
   currentRoute:'xyz',
   route:'abc/xyz'
}]
}

假设 _id:1,如果路由从 'abc' 更新为 'mno' ,那么所有子节点都应该更新他们的 parentRoute 和路由。

  {
    _id:1,
    route:'mno',
    children:[
   {
       _id:2,
       parentRoute:'mno',
       currentRoute:'xyz',
       route:'mno/xyz'
    }]
}

随意提出不同的方法!! 我什至想到了 Regex $replaceOne,但我再次遇到了 Mongo4.0 实施的困难。

【问题讨论】:

标签: mongodb api mongoose mongodb-query


【解决方案1】:

对于 OP 的 MongoDB 4.0,我们可以做一个聚合来设置相关字段:

  1. 更新route字段很简单

  2. $map 更新children.parentRoute

  3. 在步骤 2 中的 $map 内,

    3.1。执行$splitchildren.route/ 字符分解为数组

    3.2。在数组上执行$map 以将abc 替换为mno $cond

    3.3。用$replace将替换后的数组重新加入字符串

    3.4。结果字符串将带有标题'/',将其删除$ltrim

db.collection.aggregate([
  {
    $set: {
      // input mno here
      route: "mno",
      children: {
        "$map": {
          "input": "$children",
          "as": "c",
          "in": {
            _id: "$$c._id",
            // input mno here
            parentRoute: "mno",
            currentRoute: "$$c.currentRoute",
            route: {
              "$ltrim": {
                "input": {
                  "$reduce": {
                    "input": {
                      $map: {
                        input: {
                          $split: [
                            "$$c.route",
                            "/"
                          ]
                        },
                        as: "r",
                        in: {
                          "$cond": {
                            "if": {
                              $eq: [
                                "$$r",
                                "abc"
                              ]
                            },
                            "then": "mno",
                            "else": "$$r"
                          }
                        }
                      }
                    },
                    "initialValue": "",
                    "in": {
                      "$concat": [
                        "$$value",
                        "/",
                        "$$this"
                      ]
                    }
                  }
                },
                "chars": "/"
              }
            }
          }
        }
      }
    }
  }
])

最后将 JS 更新为 $merge 或在 MongoDB 4.0 中使用聚合管道进行更新尚未准备好。

db.collection.aggregate([...]).forEach(result => {
    db.collection.update({_id: result._id}, {$set: {children: result.children}})
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 2011-08-07
    • 2011-05-17
    • 2015-05-02
    • 2020-02-27
    相关资源
    最近更新 更多