【问题标题】:Replace character while copy from one column to another column mongodb从一列复制到另一列mongodb时替换字符
【发布时间】:2020-11-01 03:12:45
【问题描述】:

我想将一列值复制到另一列,为此我正在使用下面的查询,它工作正常

db.collection.aggregate(
    [
        { "$addFields": { 
            "mobile": "$user_mobile"
        }},
        { "$out": "collection_name" }
    ]
)

现在我的 user_mobile 列可能有 + 和 - 内部值。例如 +91-1234567890。所以对于这个号码,只有 911234567890 应该被复制到移动列。 如果 user_mobile 号码没有 + 和 - 内部值,那么这个 user_mobile 号码应该照原样复制 例如 1234567890 。它应该将相同的数字复制到移动列

请向我提出相同的查询

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework


    【解决方案1】:

    你可以使用这样的东西

    1. 检查手机号码是否以+开头,如果确实执行了以下步骤,否则返回手机号码
    2. 使用$substr 运算符从一开始就修剪+
    3. 使用$split 将数字拆分为-,然后使用$concat 连接它们。
    db.collection.aggregate([
      {
        "$project": {
          "mobile": {
            "$cond": {
              "if": {
                "$eq": [
                  {
                    "$substr": [
                      "$key",
                      0,
                      1
                    ]
                  },
                  "+"
                ]
              },
              "then": {
                "$concat": [
                  {
                    "$arrayElemAt": [
                      {
                        "$split": [
                          {
                            "$substr": [
                              "$key",
                              1,
                              -1
                            ]
                          },
                          "-"
                        ]
                      },
                      0
                    ]
                  },
                  {
                    "$arrayElemAt": [
                      {
                        "$split": [
                          {
                            "$substr": [
                              "$key",
                              1,
                              -1
                            ]
                          },
                          "-"
                        ]
                      },
                      1
                    ]
                  }
                ]
              },
              "else": "$key"
            }
          }
        }
      }
    ])
    

    在这里测试:https://mongoplayground.net/p/gsEYJ3KN1Dw

    注意:查询不是最佳解决方案,可以优化。我尝试使用version 3.6中可用的运算符

    【讨论】:

    • 我想我在使用$split 运算符时忘记使用$,它现在应该可以正常工作了
    • 显示错误 {"ok":0,"errmsg":"Unrecognized expression '$trim'","code":168,"codeName":"InvalidPipelineOperator"}:aggregatefailed跨度>
    • 我在分享之前测试了它,你可以在这里查看mongoplayground.net/p/o7pti4TcZx4。你用的是哪个版本的mongodb?
    • 我的mongo版本是v3.6.17
    • 这就是问题所在,因为$trimversion 4.0 中可用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2021-12-12
    • 2016-03-15
    相关资源
    最近更新 更多