Mongodb:项目只从字符串中获取数值

问题描述 投票:1回答:1

是否有任何逻辑作为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"
   }
javascript mongodb nosql
1个回答
0
投票

您可以使用聚合框架分三步完成:

  1. 使用$map$range将您的字符串转换为字符数组与$substrCP
  2. 使用$filter只保留数值("0" - "9"
  3. 使用$reduce将它们连接成一个字符串 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"] } } } } } ])
© www.soinside.com 2019 - 2024. All rights reserved.