node.jsmongooseaggregateaggregate-functionsaggregation

$filter is not allowed or the syntax is incorrect


I have some customers details. The schema is as below:

const CustSchema=new Schema({ 
    cust_name:{
        type:String,
        required:true
    },
    email:{
         type:String,
         required:true
     },
     age:{
        type:Number,
        required:true
     },
     city:{
        type:String,
        required:true
     }
},{
    timestamps: true,
    versionKey: false
})

const CustModel = new mongoose.model("cust_details", CustSchema); 

I was trying to fetch customers according to age limit. The code is:

const filterByAge = async (req, res) => {
  try{
  console.log("Age range:", req.params.age_range);
  let customers = await CustModel.aggregate([
    {
      $filter: {
        input: "$cust_details",
        cond: {
          $lte: ["$$cust_details.age", req.params.age_range],
        },
      },
    },
  ]);
  console.log(customers);
}catch(err){
  console.log("error in filter by age",err);
}
};

But it is throwing error: error in filter by age MongoServerError: $filter is not allowed or the syntax is incorrect

Please help to solve.


Solution

  • $filter is used within an array but not the collection.

    Not sure if I've understood correctly your query but I think you only need $match.

    Try something like this:

    CustModel.aggregate([
      {
        $match: {
          age: {
            $lte: req.params.age_range
          }
        }
      }
    ])
    

    Example here

    By the way, if aggreagtion is not mandatory I think is a best solution just use find like this:

    CustModel.find({
      age: {
        $lte: req.params.age_range
      }
    })
    

    Example here