美文网首页
mongodb对字符串类型字段转换成数字进行比较查询

mongodb对字符串类型字段转换成数字进行比较查询

作者: Time一柒 | 来源:发表于2022-01-17 16:03 被阅读0次

    字符串转换成数值进行查询

    数据

    {
        "_id": ObjectId("61e4e80a55170000420035a7"),
        "a": "6",
        "v": "8"
    }
    {
        "_id": ObjectId("61e4e80a55170000420035a7"),
        "a": "6",
        "v": "20"
    }
    {
        "_id": ObjectId("61e51e0355170000420035a8"),
        "a": "6",
        "v": "2021-01-06"
    }
    
    db.test_list.aggregate([
        // 将字符串转换成double数值
        {"$project":{"a":1,"v":{"$convert":{"input":"$v","to":"double", "onError": "$v","onNull":"missing time"}} }},
        //查询大于等于20的
        {"$match": {"v":{"$gte":20}}}
    ])
    

    $convert (字段类型转换)

    {"$project":{"a":1,"v":{"$convert":{"input":"$v","to":"double", "onError": "$v","onNull":"missing time"}} }
    
    {
       $convert:
          {
             input: "来源字段",
             to: “准备转换成的类型”,
             onError: "如果无法转换则输出",  // Optional.
             onNull: "如果字符串不存在则输出"    // Optional.
          }
    }
    
    
    • 支持的转换成的数据类型

    "double"
    1
    "string"
    2
    For more information on the conversion to string, see Converting to a String.
    "objectId"
    7
    For more information on the conversion to objectId, see Converting to an ObjectId.
    "bool"
    8
    For more information on the conversion to boolean, see Converting to a Boolean.
    "date"
    9
    For more information on the conversion to date, see Converting to a Date.
    "int"
    16
    For more information on the conversion to integer, see Converting to an Integer.
    "long"
    18
    For more information on the conversion to long, see Converting to a Long.
    "decimal"
    19
    For more information on the conversion to decimal, see Converting to a Decimal.

    相关文章

      网友评论

          本文标题:mongodb对字符串类型字段转换成数字进行比较查询

          本文链接:https://www.haomeiwen.com/subject/rmvchrtx.html