查询 运行 时删除 mongo 聚合中的特殊字符
Remove special characters in mongo aggregate while query run
我想从 mongo 获取所有数据,同时我需要替换特殊字符,但在查询 运行:
时不重写数据
数据库中的数据:
[{
number: "12/34",
type: "string"
},
{
number: "56-78",
type: "string"
},
{
number: "910*2",
type: "string"
}]
我要查询的号码是:1234, 5678
相关输出为:
[{
number: "12/34",
type: "string"
},
{
number: "56-78",
type: "string"
}]
我尝试添加没有特殊字符的临时字段,但我无法删除所有这些字段,因为 addfield 不处理正则表达式。我尝试使用 reduce 来做到这一点,但它对我不起作用。
有人可以帮帮我吗?
使用MongoDB v4.2+,可以使用$regexFindAll
定位所有数字。使用 $reduce
和 $concat
重构具有特殊字符 removed/sanitized 的字符串。对经过清理的字符串执行搜索。
db.collection.aggregate([
{
"$addFields": {
"sanitized": {
"$regexFindAll": {
"input": "$number",
"regex": "\d"
}
}
}
},
{
"$addFields": {
"sanitized": {
"$reduce": {
"input": "$sanitized.match",
"initialValue": "",
"in": {
"$concat": [
"$$value",
"$$this"
]
}
}
}
}
},
{
"$match": {
$expr: {
"$in": [
"$sanitized",
[
"1234",
"5678"
]
]
}
}
},
{
"$project": {
sanitized: false
}
}
])
这里是Mongo playground供您参考。
我想从 mongo 获取所有数据,同时我需要替换特殊字符,但在查询 运行:
时不重写数据数据库中的数据:
[{
number: "12/34",
type: "string"
},
{
number: "56-78",
type: "string"
},
{
number: "910*2",
type: "string"
}]
我要查询的号码是:1234, 5678
相关输出为:
[{
number: "12/34",
type: "string"
},
{
number: "56-78",
type: "string"
}]
我尝试添加没有特殊字符的临时字段,但我无法删除所有这些字段,因为 addfield 不处理正则表达式。我尝试使用 reduce 来做到这一点,但它对我不起作用。 有人可以帮帮我吗?
使用MongoDB v4.2+,可以使用$regexFindAll
定位所有数字。使用 $reduce
和 $concat
重构具有特殊字符 removed/sanitized 的字符串。对经过清理的字符串执行搜索。
db.collection.aggregate([
{
"$addFields": {
"sanitized": {
"$regexFindAll": {
"input": "$number",
"regex": "\d"
}
}
}
},
{
"$addFields": {
"sanitized": {
"$reduce": {
"input": "$sanitized.match",
"initialValue": "",
"in": {
"$concat": [
"$$value",
"$$this"
]
}
}
}
}
},
{
"$match": {
$expr: {
"$in": [
"$sanitized",
[
"1234",
"5678"
]
]
}
}
},
{
"$project": {
sanitized: false
}
}
])
这里是Mongo playground供您参考。