Can you help me with a situation… I Have this Json but I would like to format the field trackingID like "TR000000012345BR". How can I pad a trackingId with letters and zeros on the left and letter on the rigth by aggregate?
[
{
"_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"
}
]
I would like this result below:
[
{
"_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
Answers
You can do the followings in an aggregation pipeline:
$concat
$substrCP
. Use$strLenCP
and$subtract
to calculate the offset.$concat
with the prefix ‘TR’ and suffix ‘XP’Mongo Playground
Demo