Black Heart
Black Heart

Reputation: 649

MongoDB query on a field with integer value

I'm trying to do a find query using a string and a number as fields. The query works while looking for the string alone. How can I make it work for number as well?

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");
    }
});

A sample collection is given below

> db.users.find()
{ "_id" : ObjectId("608be0dc8b83df0248ed2fc1"), "name" : "John", "age" : "18", "gender" : "M", 
"country" : "RR", "socketid" : "1",
"token" : "5907" }

Upvotes: 1

Views: 1666

Answers (2)

sofa_maniac
sofa_maniac

Reputation: 1657

The token field is probably stored as a string in the database, not as a number. Look at the commas.

"token" : "5907"  

Try converting tok to a string in the query.

find({'name':check, 'token':String(tok)})

Upvotes: 2

turivishal
turivishal

Reputation: 36154

You can use expression $expr condition to make sure hundred percent whatever token has type string or number,

  • $toInt to convert string to number
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");
    }
});

Playground

Upvotes: 2

Related Questions