Closed tquoctuan97 closed 3 weeks ago
After running this script, all bills documents should have prePay
and debt
values moved into the adjustmentList
, and the old fields should be kept for reference.
db.bills.aggregate([
{
$addFields: {
adjustmentList: {
$concatArrays: [
{ $ifNull: ['$adjustmentList', []] },
{
$filter: {
input: [
{
$cond: {
if: { $ne: ['$prePay', null] },
then: {
name: 'Prepay',
type: 'subtract',
amount: '$prePay',
},
else: null,
},
},
{
$cond: {
if: { $ne: ['$debt', null] },
then: {
name: 'Debt',
type: 'add',
amount: '$debt',
},
else: null,
},
},
],
as: 'item',
cond: { $ne: ['$$item', null] },
},
},
],
},
},
},
{
$merge: {
into: 'bills',
on: '_id',
whenMatched: 'merge',
whenNotMatched: 'discard',
},
},
]);
Let's break down this script:
We use the aggregate
pipeline for more complex operations:
$addFields
: We're adding or modifying the adjustmentList
field.$concatArrays
: We concatenate the existing adjustmentList
(or an empty array if it doesn't exist) with new items.$filter
: We create new items only if prePay
or debt
are not null.$cond
: We use conditional operators to create the new adjustment items.The $merge
stage writes the results back to the bills
collection, updating existing documents.
Adjustment List Documentation
Introduction
The
adjustmentList
is a feature of our billing system that allows for flexible application of additional fees and discounts to a bill. This document explains its purpose, structure, and usage.Purpose of
adjustmentList
Additional Fees: If there are extra charges that need to be added to the total bill, such as service fees, delivery charges, etc., these can be represented as entries in the
adjustmentList
with thetype
set to"add"
.Discounts: If there are discounts applied to the bill, these can be represented with the
type
set to"subtract"
.Structure and Fields
name
: A string describing the fee or discount.type
: A string indicating whether it's an addition ("add"
) or subtraction ("subtract"
).amount
: A number representing the value of the fee or discount.This structure allows the user to manage and apply various fees and discounts to a bill.
Example
Here's an example of a complete bill structure using
adjustmentList
:Calculation
To calculate the final result:
adjustmentList
:Migration Data
Currently, we have
prepay
anddebt
fields in the Bill document. After implementing the changes, we need to migrate the old data to the newadjustmentList
structure.Old
New