简体   繁体   中英

$subtract not working with $set in mongodb

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

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM