Mongoose - update field with field value from other document

Viewed 122

I am using mongoose to access and modify data in my Mongo DB. Each document contains date and amount. I would like to add to each document the amount corresponding to the most recent date before the date of the document (i.e. previous_amount). Since the 'first' document doesn't have a preceding document, I would store a default value.

Can somebody help me with this?

See an example below. In the example the documents are already ordered on date, but this is not necessarily the case in my actual implementation.

Current values

[    
    {
        "_id": {
            "$oid": "0001"
        },
        "date": {
            "$date": "2020-01-12"
        },
        "amount": 100
    },
    {
        "_id": {
            "$oid": "0002"
        },
        "date": {
            "$date": "2020-11-18"
        },
        "amount": 300
    },
    {
        "_id": {
            "$oid": "0003"
        },
        "date": {
            "$date": "2020-11-20"
        },
        "amount": 250
    }
]

Target values

[    
    {
        "_id": {
            "$oid": "0001"
        },
        "date": {
            "$date": "2020-01-12"
        },
        "amount": 100,
        "previous_amount": 999,
    },
    {
        "_id": {
            "$oid": "0002"
        },
        "date": {
            "$date": "2020-11-18"
        },
        "amount": 300,
        "previous_amount": 100,
    },
    {
        "_id": {
            "$oid": "0003"
        },
        "date": {
            "$date": "2020-11-20"
        },
        "amount": 250,
        "previous_amount": 300,
    }
]
0 Answers
Related