MongoDB 聚合 - 如何在左侧填充零和字母的字段?

问题描述 投票:0回答:2

你能帮我解决一个问题吗……我有这个 Json,但我想格式化字段 trackingID,如 “TR000000012345BR”。我如何通过聚合在左侧用字母和零填充 trackingId,在右侧用字母填充?

[
  {
    "_id": "63f7aad063710fe0106dbc04",
    "name": "Kristen Welch",
    "address": "267 Dooley Street, Westphalia, New York, 1648",
    "trackingID": 963,
    "greeting": "Hello, Kristen Welch! You have 9 unread messages.",
    "favoriteFruit": "apple"
  },
  {
    "_id": "63f7aad0c156afad133a66b6",
    "name": "Shaw Roach",
    "address": "254 Newkirk Placez, Hiseville, American Samoa, 7644",
    "trackingID": 729,
    "greeting": "Hello, Shaw Roach! You have 7 unread messages.",
    "favoriteFruit": "banana"
  }
]

我想要下面这个结果:

[
  {
    "_id": "63f7aad063710fe0106dbc04",
    "name": "Kristen Welch",
    "address": "267 Dooley Street, Westphalia, New York, 1648",
    "trackingID": TR0000000963XP,
    "greeting": "Hello, Kristen Welch! You have 9 unread messages.",
    "favoriteFruit": "apple"
  },
  {
    "_id": "63f7aad0c156afad133a66b6",
    "name": "Shaw Roach",
    "address": "254 Newkirk Placez, Hiseville, American Samoa, 7644",
    "trackingID": TR0000000729XP,
    "greeting": "Hello, Shaw Roach! You have 7 unread messages.",
    "favoriteFruit": "banana"
  }
]

https://mongoplayground.net/p/8uUd7DVcW9R

mongodb mongodb-query aggregation-framework aggregate projection
2个回答
0
投票

您可以在聚合管道中执行以下操作:

  1. 在字符串的开头用
    $concat
  2. 填充 9 个零
  3. $substrCP
    修剪多余的前导零。使用
    $strLenCP
    $subtract
    计算偏移量。
  4. $concat
    带有前缀“TR”和后缀“XP”
db.collection.aggregate([
  {
    "$set": {
      "trackingID": {
        // pad with 9 zeros
        "$concat": [
          "000000000",
          {
            $toString: "$trackingID"
          }
        ]
      }
    }
  },
  {
    "$set": {
      "trackingID": {
        // trim the extras leading zeros
        "$substrCP": [
          "$trackingID",
          {
            "$subtract": [
              {
                "$strLenCP": "$trackingID"
              },
              9
            ]
          },
          9
        ]
      }
    }
  },
  {
    "$set": {
      "trackingID": {
        "$concat": [
          "TR",
          "$trackingID",
          "XP"
        ]
      }
    }
  }
])

Mongo 游乐场


0
投票
db.collection.aggregate([
  {
    $set: {
      "trackIngID": {
        $concat: [                                  //4. concatenate prefix and suffix
          "TR",
          {
            "$substrCP": [                          //3. remove leading 1
              {
                $toLong: {                          //2. convert to long
                  $add: [10000000000,"$trackingID"] //1. add 10000000000, to pad it with zeros
                }
              },
              1,
              10
            ]
          },
          "XP"
        ]
      }
    }
  }
])

演示

© www.soinside.com 2019 - 2024. All rights reserved.