1

I have the following code:

 var dates = getDates();
        var a = dates.now;
        var tomorrow = dates.tomorrow;

        console.log("{userid: " + userid + ", time: {$gte: " + a + "}, time: {$lte: " + tomorrow +"}");
        tickets.find({userid: userid, time: {$gte: a}, time: {$lte: tomorrow}}).then(function (usertickets) {
            console.log(usertickets[0]);
            return resolve(usertickets);
        });

console log:

     {userid: 57e0fa234f243f0710043f8f, time: {$gte: 1476309600000}, time: 
{$lte: 1476396000000}

console log result output:

{ userid: '57e0fa234f243f0710043f8f',
  username: 1,
  fromticket: 1,
  amount: 1,
  toticket: 2,
  time: '1474362076461',
  __v: 0,
  _id: 57e0fadce32462ca1036274d }

Q: How come that time 1474362076461 is in results, while it should be results greather or equal to 1476309600000 and lower than 1476396000000 ?

maria
  • 207
  • 5
  • 22
  • 56

2 Answers2

1

You have numeric value as string and when you compare numeric values in string then it works different for ex.

console.log('2'>'11')

it will print true. so change your schema to Number.

Sachin
  • 2,912
  • 16
  • 25
1

Your current query

{
    userid: userid, 
    time: {$gte: a}, /* MongoDB ignores this first expression */
    time: {$lte: tomorrow}
}

returns a document with a time value 1474362076461 because when a query is structured the way you did, MongoDB ignores the first key expression time: {$gte: a} and evaluates the JSON as

{
    userid: userid, 
    time: {$lte: tomorrow}
}

and

'1474362076461' <= 1476396000000 

evaluates to true so essentially it queries the collection on the time field part using the $lte comparison and ignores the other duplicate key. For in-depth info on the validity of the above JSON, refer to this question Does JSON syntax allow duplicate keys in an object?


As a fix, you need to keep the two comparison operators under one key so that your query object becomes valid JSON and the comparison operators are embedded within a subdocument i.e. your query should be

{
    userid: userid, 
    time: { $gte: a, $lte: tomorrow }
}

for this to work.

Also, you should be aware that you are comparing a your field with a different type as the time field in your db is a string and in the above you are comparing it with an integer. MongoDB treats some types as equivalent for comparison purposes. For instance, numeric types undergo conversion before comparison hence the query works just as fine.

For more details, refer to the documentation on Comparison/Sort Order.

Community
  • 1
  • 1
chridam
  • 100,957
  • 23
  • 236
  • 235