proquibas
proquibas

Reputation: 91

mongodb find with calculated field

I'm trying to create a mongodb query using the filtered value in the filter. For example:

   var myIdVariable = '1jig23h34r34r30h';
   var myVisibleVariable = false;
   var myDistanceVariable = 100;

   db.getCollection.find({
        '_id': myIdVariable,
        'isVisible': myVisibleVariable,
        'distanceRange': {$lte: {myDistanceVariable - distanceRange}}
    })

So, I want filter the distanceRange from database based on the calculation of (myDistanceVariable - distanceRange), with the distanceRange given in the same query. I don't know if I give you a clear explanation of my problem. It's possible?

Thanks you.

Upvotes: 1

Views: 1924

Answers (1)

chridam
chridam

Reputation: 103365

Use the $expr operator to build a query expression that allows you to compare fields from the same document as well as compare the distanceRange field with the calculation of the field itself and your variables.

You would need to use the logical $and query operator to include the other query expressions thus your final query would look like the following:

db.getCollection('collectionName').find({
    '$expr': {
        '$and': [
            { 'isVisible': myVisibleVariable },
            { '$lte': [
                '$distanceRange', {
                    '$subtract': [
                        myDistanceVariable, '$distanceRange'
                    ]
                }
            ] }
        ]
    }
})

If your MongoDB server doesn't support the $expr operator then go for the aggregation framework route with $redact

db.getCollection('collectionName').aggregate([
    { "$redact": {
        "$cond": [
            {   
                '$and': [
                    { 'isVisible': myVisibleVariable },
                    { '$lte': [
                        '$distanceRange', {
                            '$subtract': [
                                x, '$distanceRange'
                            ]
                        }
                    ] }
                ]
            },
            "$$KEEP",
            "$$PRUNE"
        ]
    } }
])

Note

Including the _id in the query expressions means you are narrowing down your selection to just a single document and the query may not return any results since it's looking for a specific document with that _id AND the same document should satisfy the other query expressions.

Upvotes: 2

Related Questions