MongoDB Aggregation -如何在字段的左边填充零和字母?

8fsztsew  于 2023-03-01  发布在  Go
关注(0)|答案(2)|浏览(147)

您能帮我解决一个问题吗...我有这个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

gj3fmq9x

gj3fmq9x1#

您可以在聚合管道中执行以下操作:
1.用$concat在字符串开头填充9个零
1.使用$substrCP修剪多余的前导零。使用$strLenCP$subtract计算偏移。
1.带有前缀"TR"和后缀"XP"的$concat

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 Playground

yqkkidmi

yqkkidmi2#

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"
        ]
      }
    }
  }
])

Demo

相关问题