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.
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();
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With