简体   繁体   中英

findAndModify conditionally in mongoDB

I want to update the promotional value if it is greater than the credit I want to set it to 30 , else I want it to set to 20 .

Document

    {
        "_id" : "XX",    
        "promotional" : 200,    

    }

Code

let creditDeduct= 100
let accountId = 'xx'

this.adapter.collection.findAndModify(
    _id = accountId, 
    [["_id", "asc"]], 
    { "$inc": { $cond: { if: { $gte: [ '$promotional', creditDeduct ] }, then: 30, else: 20 }} },
    { "new": true, "upsert": true }, 
    function(error, doc) { 
        if (doc) {
                console.log(doc);
                } 
            if(error){
                console.log(error);
            }
            }
);

Error

{ MongoError: Cannot increment with non-numeric argument: {$cond: { if: { $gte: [ "$promotional", 100 ] }, then: 30, else: 20 }}
    at Connection.<anonymous> (/xx/xx/node_modules/mongodb/lib/core/connection/pool.js:466:61)
    at Connection.emit (events.js:198:13)
    at processMessage (/xx/xx/node_modules/mongodb/lib/core/connection/connection.js:364:10)
    at Socket.<anonymous> (/xx/xx/node_modules/mongodb/lib/core/connection/connection.js:533:15)
    at Socket.emit (events.js:198:13)
    at addChunk (_stream_readable.js:288:12)
    at readableAddChunk (_stream_readable.js:269:11)
    at Socket.Readable.push (_stream_readable.js:224:10)
    at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)   ok: 0,   errmsg:    'Cannot increment with non-numeric argument: {$cond: { if: { $gte: [ "$promotional", 100 ] }, then: 30, else: 20 }}',   code: 14,   codeName: 'TypeMismatch',   name: 'MongoError',   [Symbol(mongoErrorContextSymbol)]: {} }

When you want to set the value you will need to use set

var credit= 100
db.collection.updateMany({"promotional":{$gt:credit}},{$set:{"promotional":20}})
db.collection.updateMany({"promotional":{$lte:credit}},{$set:{"promotional":30}})

Also, $inc will be only applicable to numeric data types. Can you check if the promotional value is a number and not a string ?

In Mongo Compass you can click on edit button to set its data type.

See below example where I put it as int64: 请参阅下面的示例,我将其设置为 int64

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