How to put validation on Calculated Field?

Hii

Currently I have created a calculated field in my mongodb collection with following calculation:

total_orders = len('orders_list')
total_amount = summation of all 'amount' present in each item of 'orders_list'
total_tax = summation of all 'tax_amount' present in each item of 'orders_list'

Now I need to keep a validator that will validate above calculated field. Is there any way to create a validation that can keep track on this calculations?

Hi @Mehul_Sanghvi!

It’s possible to create a schema validation for the collection that will check if the fields for totals have the expected values. You can implement it using the $expr on the schema validation logic. Here you can find out more about this topic.

I believe the following validation logic will work for total_orders and total_amount:

db.createCollection('<your-collection>', {
  validator: {
    $expr: {
      $and: [
        { $eq: ['$total_orders', { $size: '$orders_list' }] },
        {
          $eq: [
            '$total_amount',
            {
              $reduce: {
                input: '$total_orders',
                initialValue: 0,
                in: { $sum: ['$$value', '$$this.amount'] },
              },
            },
          ],
        },
      ],
    },
  },
});