Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Conditional Projection

Tags:

mongodb

I would like to conditonally leave out fields in a response.

I have an aggregation query which uses geoNear to find the nearest POI and I would like to only retreive all the information if the distance between the query point and the POI is less than 500.

Let's assume I want to leave out "someField" if the distance is less than or equal to 500.

Here is what I have come up with:

db.pois.aggregate([
    { 
        "$geoNear": {
        "near": {
                type: "Point", 
                coordinates: [49.607857, 6.129143]
        }, 
        "maxDistance": 0.5 * 1000,
        "spherical": true,
        "distanceField": "distance"
        }
    }, {
        $project: {
            _id:0,
            "someField": {
                $cond: [{$lte: ["$distance", 500]}, 1, 0 ]
            }
        }
    } 
]).pretty()

But instead of leaving the field out of the response, this query somehow replaces the value of "distance" with 0 or 1.

I would appreciate any help.

like image 680
LostSoul Avatar asked Jan 01 '23 07:01

LostSoul


1 Answers

Starting in MongoDB 3.6, you can use the variable REMOVE in aggregation expressions to conditionally suppress a field.

$$REMOVE

Query:

db.pois
  .aggregate([
    {
      $geoNear: {
        near: {
          type: "Point",
          coordinates: [49.607857, 6.129143]
        },
        maxDistance: 0.5 * 1000,
        spherical: true,
        distanceField: "distance"
      }
    },
    {
      $project: {
        _id: 0,
        someField: {
          $cond: {
            if: { $lte: ["$distance", 500] },
            then: "$$REMOVE",
            else: "$distance"
          }
        }
      }
    }
  ])
  .pretty();
like image 181
ambianBeing Avatar answered Jan 09 '23 15:01

ambianBeing