0

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)]: {} }

1 Answers1

0

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: See below example where I put it as int64

Syntle
  • 5,168
  • 3
  • 13
  • 34
  • Thanks.but i want to check greater than,less than in one condition and update query when record match to `accountId` – Yasiru Attanayake Apr 18 '20 at 04:21
  • Mongo doesn't support combining fields, conditionals etc. in the update statement. Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update/creation of a field based on another field. Please reefr to below for more detail...https://stackoverflow.com/questions/36698569/mongodb-update-with-condition/56551655 – Programmer Analyst Apr 20 '20 at 02:58