是否有任何逻辑作为javascript替换(/ [^ \ d。] / g,'')方法。只获取字符串的数值。
从字符串中只获取整数
样本文件:
{
"_id" : "1",
"planName" : "Options Silver 1431B"
}
{
"_id" : "1",
"planName" : "Options Silver 1431A"
}
{
"_id" : "1",
"planName" : "myOptions 1431A"
}
{
"_id" : "1",
"planName" : "myOptions 1431"
}
{
"_id" : "1",
"planName" : "myOptions 1431A",
}
结果:
{
"_id" : "1",
plan_id: "1431"
},
{
"_id" : "1",
plan_id: "1431"
},
{
"_id" : "1",
plan_id: "1431"
},
{
"_id" : "1",
plan_id: "1431"
},
{
"_id" : "1",
plan_id: "1431"
}
您可以使用聚合框架分三步完成:
"0"
- "9"
)db.col.aggregate([
{
$addFields: {
chars: {
"$map":{
"input":{
"$range":[
0,
{
"$strLenCP":"$planName"
}
]
},
"in":{
"$substrCP":[
"$planName",
"$$this",
1
]
}
}
}
}
},
{
$project: {
numbers: {
$filter: {
input: "$chars",
as: "char",
cond: { $and: [
{ $gte: [ "$$char", "0" ] },
{ $lte: [ "$$char", "9" ] }
] }
}
}
}
},
{
$project: {
plan_id: {
$reduce: {
input: "$numbers",
initialValue: "",
in: { $concat : ["$$value", "$$this"] }
}
}
}
}
])