您能帮我解决一个问题吗...我有这个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"
}
]
2条答案
按热度按时间gj3fmq9x1#
您可以在聚合管道中执行以下操作:
1.用
$concat
在字符串开头填充9个零1.使用
$substrCP
修剪多余的前导零。使用$strLenCP
和$subtract
计算偏移。1.带有前缀"TR"和后缀"XP"的
$concat
Mongo Playground
yqkkidmi2#
Demo