Tuesday 9 May 2017

Use calculated fields to calculate new field in $project with MongoDB

I have a collection Item with fields _id, price, and project as well as a collection Project with fields _id and name.

The items have different prices, so I want to group the items by price and count how many items are in each group and save the value as quantity.

Then I want to compute quantity and price to get the total amount. But I want to calculate some fees. The fees should be computed as totalPrice * (1 + 10/100) + 5 * quantity.

So I have tried using $project to calculate each fee and it works, but I cannot create a final calculated field with the total price including the fees. I think I am not able to use a calculated field in the same $project?

I have used the following code, but totalPriceWithFees becomes 0:

Item.aggregate([
  {
    $group: {
      _id: {
        project: '$project',
        price: '$price'
      },
      quantity: { $sum: 1 }
    }
  },
  {
    $project: {
      quantity: 1,
      totalPriceWithoutFees: {
        $multiply: ['$_id.price', '$quantity']
      },
      feesPercentage: {
        $multiply: ['$_id.price', 0.1]
      },
      feesAbsolute: {
        $multiply: ['$quantity', 5]
      },
      fees: {
        $sum: ['feesPercentage', 'feesAbsolute']
      },
      totalPriceWithFees: {
        $sum: ['$totalPriceWithoutFees', '$fees']
      },
    }
  }
  {
    $lookup: {
      from: 'Project',
      localField: '_id.project',
      foreignField: '_id',
      as: 'project'
    }
  }
])

Also, I want to populate the project. I have only saved the project id, so I need to populate to get the project name. I am not sure if it's possible with normal populate() in Mongoose, so I have tried using $lookup, but it also doesn't work. The field project just becomes empty.



via Jamgreen

No comments:

Post a Comment