skip to Main Content

Hello Im having a weird issue

Ive looked in a few previous questions but ive ran into an issue

Basically I have a document containing a boolean

This boolean is called enabled

Id like to switch it using the findOneAndUpdate function

{ $set: { enabled: { $not: "$enabled" } } }

This is what ive come to according to previous questions

However when I attempt it this is the result

enabled: { '$not': '$enabled' }

Here is my full code

db.findOneAndUpdate({
    _id: "Sample"
}, {
    $set: {
        enabled: {
            $not: "$enabled"
        }
    }
}, {
    new: true
}, function(err, result) {})

2

Answers


  1. You can use the $bit operator to toggle the value of the enabled field.

    db.findOneAndUpdate({
        _id: "Sample"
    }, {
       { $bit: { enabled: { xor: 1 } } }
    }, {
        new: true
    }, function(err, result) {})
    

    On each update, the value enabled will toggle (1 to 0, 0 to 1).

    Alternatively, you can use the set method as thus:

     db.findOneAndUpdate({
                _id: "Sample"
            }, [{
        $set: {
            enabled: {
                $not: "$enabled"
            }
        }
    }], {
          new: true
            }, function(err, result) {})
    
    Login or Signup to reply.
  2. The problem is that you are trying to use the $not aggregation operator inside of a legacy update.

    In order to use aggregation operators you will need to use Updates with Aggregation Pipeline.

    For your example, this should be as simple as wrapping the update in an array like:

    db.findOneAndUpdate({
        _id: "Sample"
    },[{
        $set: {
            enabled: {
                $not: "$enabled"
            }
        }
    }], {
        new: true
    }, function(err, result) {})
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search