Home > Enterprise >  Using math function in projections in mongodb
Using math function in projections in mongodb

Time:11-09

Using Node and Mongoose Trying to fetch data from a collection in which field days is having negative as well as positive numbers stored. I want to show all the data of days in positive only, so therefore using Math abs function. but somehow it is not working and also not showing any error.

Code is below:

        let projection = {
        _id : 0,
        userId : 1,
        sum : 1,
        days : Math.abs("$days"), //This is not working
        leaveType : 1,
        reason : 1,
        fromDate : 1,
        toDate : 1,
        leaveDuration : 1,
        leaveStatus : 1,
        createdAt : 1,
        updatedAt : 1,
        rejectReason : 1,
        empName : "$userDetails.fullName",
        leaveType : "$LeaveDetails.leaveTitle",
        availableBalance : 1,
    }

CodePudding user response:

$abs (aggregation) is what you are looking for. link : https://docs.mongodb.com/manual/reference/operator/aggregation/abs/

  let projection = {
    _id : 0,
    userId : 1,
    sum : 1,
    days: {$abs: "$days" } , //This will work
    leaveType : 1,
    reason : 1,
    fromDate : 1,
    toDate : 1,
    leaveDuration : 1,
    leaveStatus : 1,
    createdAt : 1,
    updatedAt : 1,
    rejectReason : 1,
    empName : "$userDetails.fullName",
    leaveType : "$LeaveDetails.leaveTitle",
    availableBalance : 1,
}
  • Related