数字比较,例如大于存储为字符串的货币金额

时间:2017-03-22 04:07:05

标签: mongodb mongodb-query

所以我有一个假银行用户的示例JSON文件,我想找到余额超过1000美元的人,我该怎么办?请记住,余额是一个字符串值。 示例用户信息:

{
    "_id" : ObjectId("58d1cae3cba624106c8080ab"),
    "isActive" : false,
    "balance" : "$3,495.58",
    "age" : 24,
    "eyeColor" : "blue",
    "name" : "Webster Sanders",
    "gender" : "male",
    "company" : "HALAP",
    "email" : "webstersanders@halap.com",
    "phone" : "+1 (883) 536-2259",
    "address" : "300 Jewel Street, Sugartown, Federated States Of Micronesia, 9305"
}

5 个答案:

答案 0 :(得分:1)

您可以使用正则表达式,如:

db.users.find({ balance: { $regex: /^\$[1-9][0-9\,]{3,}/ } });

答案 1 :(得分:0)

通过将货币值存储为字符串,您将使自己的生活变得非常困难。你最好离开storing it as a numeric value, possibly with a string equivalent (for presentation) in a second field if necessary

答案 2 :(得分:0)

Number(currency.replace(/ [^ 0-9 .-] + / g,“”));

答案 3 :(得分:0)

请尝试下面的代码

var currency =“-$ 4,400.50”; var number = Number(currency.replace(/ [^ 0-9 .-] + / g,“”));

答案 4 :(得分:-1)

首先在字符串中获取余额,然后将$,替换为''(空白引号),然后使用int.parse

例如:

string a = balance
a = a.replace("$","");
a = a.replace(",","");
int balance = int.parse(a);