你能帮我解决一个问题吗……我有这个 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"
}
]
您可以在聚合管道中执行以下操作:
$concat
$substrCP
修剪多余的前导零。使用 $strLenCP
和 $subtract
计算偏移量。$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"
]
}
}
}
])
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"
]
}
}
}
])