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

时间:2018-03-06 19:49:29

标签: javascript mongodb nosql

是否有任何逻辑作为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"
   }

1 个答案:

答案 0 :(得分: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"] }
                    }
                }
            }
        }
    ])