0

I am trying to calculate with some dates in my aggregation and $lookup. I was first thinking of using a function within the aggregation, but JavaScript is not allowed to be used.

{
  $lookup: {
    from: "sales",
    let: { user: "$_id" },
    pipeline: [
      $project: {
        time: //// CALCULATE TIME DIFFERENCE BETWEEN $createdAt and $startedAt,
      }
    ]
    as: "sales"
  }
}

Is there any way to return something similar to this in my $project?

const calculate = (created, started) => {
    const result = moment(created).diff(moment(started))
    return result
}
vemund
  • 1,667
  • 4
  • 29
  • 43

1 Answers1

2

As I pointed out in the possible duplicate of another question, you should use one of the aggregation pipeline operators. In particular, you should use $subtract operator, that works also with dates.

{
  $lookup: {
    from: "sales",
    let: { user: "$_id" },
    pipeline: [
      $project: {
        time: { $subtract: ["$createdAt", "$startedAt"]}
      }
    ]
    as: "sales"
  }
}
oniramarf
  • 843
  • 1
  • 11
  • 27