我在 Mongo 中使用了一個帶有多個貨幣型別的價格欄位的集合:
{
price: '15 gp' // 15 gold pieces
}
或者
{
price: '4 sp' // 0.4 gold pieces
}
我正在尋找一種在查詢集合之前修改此欄位的方法。
例如,進行字串修改以洗掉gp/sp并進行數學運算以在“GP”中獲得正確的價格(1 GP = 10 SP)
這將有助于訂購集合,因為 mongo 無法理解 10 sp < 2 gp。
有沒有辦法使用聚合和正則運算式來做到這一點?
uj5u.com熱心網友回復:
首先添加新欄位rate并檢查 gp 或 sp 并放置每個價格的費率,例如 sp 的費率為 10,gp 的費率為 1,然后添加通用價格欄位與價格率和價格值的乘積,然后您可以比較價格
db.collection.aggregate([
{
"$addFields": {
"newField": {
"$split": [
"$price",
","
]
}
}
},
{
"$project": {
price: {
$reduce: {
input: "$newField",
initialValue: "",
in: {
$concat: [
"$$value",
"$$this"
]
}
}
}
}
},
{
"$addFields": {
"rate": {
"$switch": {
"branches": [
{
"case": {
"$regexMatch": {
"input": "$price",
"regex": ".*gp*."
}
},
"then": "1"
},
{
"case": {
"$regexMatch": {
"input": "$price",
"regex": ".*sp*."
}
},
"then": "10"
}
],
default: 1
}
}
}
},
{
"$project": {
price: 1,
universalPrice: {
"$multiply": [
{
"$toInt": "$rate"
},
{
"$toInt": {
$first: {
"$split": [
"$price",
" "
]
}
}
}
]
}
}
}
])
https://mongoplayground.net/p/S5EIUdWRp5W
uj5u.com熱心網友回復:
您可以使用此聚合階段來轉換price欄位值:
db.collection.aggregate([
{
$addFields: {
price: {
$function: {
body: function(inPrice) {
let outPrice;
if (/gp/.test(inPrice)) {
outPrice = parseInt(inPrice.replace("gp", "").trim()) * 10;
}
else if (/sp/.test(inPrice)) {
outPrice = parseInt(inPrice.replace("sp", "").trim());
}
else {
outPrice = inPrice; // whatever needs here...
}
return outPrice;
},
args: [ "$price" ],
lang: "js"
}
}
}
}
])
例如,price: "5 gp"將轉換為price: 50 ,并 price: "12 sp"會轉換為price: 12。請注意,這些值將轉換為數字型別欄位以進行比較和計算。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/345423.html
