SergiDP
SergiDP

Reputation: 57

Find documents with difference between field and value less than x

Suppose I have this documents:

{_id:1, value:2.21}
{_id:2, value:2.23}

Then if for example I receive a parameter which is 2.24, I want to return documents where abs(2.24-value)<=0.01 This concretely would return only the document with _id:2

So in general I want documents where abs(value-parameter)<=x

Thank you.

Upvotes: 1

Views: 785

Answers (2)

Leonardo Delfino
Leonardo Delfino

Reputation: 1498

You can not make the ABS operation directly. But you can do with a conditional operator $cond.

db.numbers.aggregate([{
   $project: {
            value: {
                $subtract: [2.24, 
                            {$cond: [{$lt: ['$value', 0]}, 
                                     {$subtract: [0, '$value']}, 
                                     '$value']
                            }
                ]
            }
        }
    }, {
    $match: {
          value: {$lte: 0.01}
    }
}]);

Use the aggregate command to perform the operation, the first step is done the projection of the absolute value, and the second step is done the condition.

Note that you may need to round off the absolute result to obtain the expected result.

Upvotes: 0

NoOutlet
NoOutlet

Reputation: 1969

This can be a simple db.coll.find() with $gte and $lte

> var foo = 2.24;
> var difference = 0.0100000000001
> db.numbers.find({value:{$gte: (foo - difference), $lte: (foo + difference)}})
{ "_id" : 2, "value" : 2.23 }

The only issue is that MongoDB uses floating point arithmetic which means that if difference was set to 0.01, the result of foo - difference might be something like 2.23000000000000004 (which would miss the second document). That's why I set it just barely above the difference that we're actually looking for.

Upvotes: 4

Related Questions