2

I am using the following query to update the documents in mongodb but it throws me the error The dollar ($) prefixed field '$subtract' in 'abc.$subtract' is not valid for storage.

const bulkUpdate = arrs.map(arr => {
        const { val = 0 } = arr
        return {
            updateMany: {
                filter: {
                    date: 20201010
                },
                update: {
                    $set: {
                        abc: {
                            $subtract: [val, { $add: [{ $ifNull: ['$a1', 0] }, { $ifNull: ['$b1', 0] } ] }]
                        }
                    },
                },
            },
        }
    })

    if (bulkUpdate.length > 0) {
        return mongoConnection.pool
            .db('test')
            .collection('testTable')
            .bulkWrite(bulkUpdate)
    }

Thanks is advance

Balaji Kondalrayal
  • 1,743
  • 3
  • 19
  • 38
  • Maybe you have a previous version of mongodb which doesn't allow to use aggregation in an update (previous to 4.2). [Here](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) you can find more information. – Álvaro Tihanyi Nov 02 '20 at 15:39

1 Answers1

0

$subtract and $ifNull are not update operators, hence you can't use them within an update (except a within a pipelined update).

If you're using Mongo version 4.2+ you can use use a pipeline update instead of a "document update" like so:

{
    updateMany: {
        filter: {
            date: 20201010
        },
        update: [
            {
                $set: {
                    abc: {
                        $subtract: [val, {$add: [{$ifNull: ['$a1', 0]}, {$ifNull: ['$b1', 0]}]}]
                    }
                }
            }
        ]
    }
}

If you aren't then you'll have to read each document and update it sepratley as prior to version 4.2 you could not access document fields while updating as you are trying to do.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43