mongodb - 对 mongodb 集合中的字段进行字符串操作(聚合和正则表达式)
问题描述
我在 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。
有没有办法使用聚合和正则表达式来做到这一点?
解决方案
首先添加新字段rate
并检查 gp 或 sp 并查看每个价格的价格,例如 sp 的价格为 10,gp 的价格为 1,然后添加 Universalprice 字段,价格乘以价格和价格值,然后您可以比较价格
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",
" "
]
}
}
}
]
}
}
}
])
推荐阅读
- c - 如何为C中的文件行分配内存?
- visual-studio-code - 如何让 cmd+c 在 macOS 的 VS Code 终端中发送 ctrl+c?
- laravel - 我正在尝试使用 HTML 创建 PDF
- php - 具有比较运算符和小数位的 PHP 脚本逻辑
- r - 根据另一个数据帧中的字符串对R中列表中的多个数据帧进行子集化
- python - AWS Lambda 初始化代码(Python)之谜
- powershell - 如何使用 PowerShell 指定 FolderBrowserDialog 中显示的初始路径
- python - 使用 Python 查找文件或 csv 中的最大列数
- javascript - 滚动显示图像:保持底部图像固定,直到完成视差覆盖,然后继续页面滚动
- java - 如何使用 gson 从 json 读取对象数组?