首页 > 解决方案 > 对 mongodb 集合中的字段进行字符串操作(聚合和正则表达式)

问题描述

我在 Mongo 中使用具有多种货币类型的价格字段的集合:

{
  price: '15 gp' // 15 gold pieces
}

或者

{
  price: '4 sp' // 0.4 gold pieces
}

我正在寻找一种在查询集合之前修改此字段的方法。

例如进行字符串修改以删除gp/sp和进行数学运算以在“GP”中获得正确的价格(1 GP = 10 SP)

这将有助于订购该系列,因为 mongo 无法理解 10 sp < 2 gp。

有没有办法使用聚合和正则表达式来做到这一点?

标签: mongodbmongodb-queryaggregation-framework

解决方案


首先添加新字段rate并检查 gp 或 sp 并查看每个价格的价格,例如 sp 的价格为 10,gp 的价格为 1,然后添加 Universalprice 字段,价格乘以价格和价格值,然后您可以比较价格

db.collection.aggregate([
  {
    "$addFields": {
      "newField": {
        "$split": [
          "$price",
          ","
        ]
      }
    }
  },
  {
    "$project": {
      price: {
        $reduce: {
          input: "$newField",
          initialValue: "",
          in: {
            $concat: [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }
  },
  {
    "$addFields": {
      "rate": {
        "$switch": {
          "branches": [
            {
              "case": {
                "$regexMatch": {
                  "input": "$price",
                  "regex": ".*gp*."
                }
              },
              "then": "1"
            },
            {
              "case": {
                "$regexMatch": {
                  "input": "$price",
                  "regex": ".*sp*."
                }
              },
              "then": "10"
            }
          ],
          default: 1
        }
      }
    }
  },
  {
    "$project": {
      price: 1,
      universalPrice: {
        "$multiply": [
          {
            "$toInt": "$rate"
          },
          {
            "$toInt": {
              $first: {
                "$split": [
                  "$price",
                  " "
                ]
              }
            }
          }
        ]
      }
    }
  }
])

https://mongoplayground.net/p/S5EIUdWRp5W


推荐阅读