[英]MongoDB query on a field with integer value
我正在尝试使用字符串和数字作为字段进行查找查询。 该查询在单独查找字符串时起作用。 我怎样才能使它也适用于数字?
var check = request.body.cookie; // String
var tok = request.body.token; // It's a number
db.collection("users").find({'name':check, 'token':tok}).toArray(function(err, rows) {
if(!rows.length)
{
console.log("No data found");
}
});
下面给出了一个样本集合
> db.users.find()
{ "_id" : ObjectId("608be0dc8b83df0248ed2fc1"), "name" : "John", "age" : "18", "gender" : "M",
"country" : "RR", "socketid" : "1",
"token" : "5907" }
token
字段可能在数据库中存储为字符串,而不是数字。 看逗号。
"token" : "5907"
尝试在查询中将tok
转换为字符串。
find({'name':check, 'token':String(tok)})
您可以使用表达式$expr条件来确保百分百任何令牌具有字符串或数字类型,
$toInt
将字符串转换为数字var check = request.body.cookie; // String
var tok = request.body.token; // It's a number
db.collection("users").find({
$and: [
{ name: check },
{
$expr: {
$eq: [{ $toInt: "$token" }, tok]
}
}
]
}).toArray(function(err, rows) {
if(!rows.length)
console.log("No data found");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.