0

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) {})
3
  • Share reproducible code example please. Commented Dec 31, 2022 at 0:34
  • You are trying to update the status of the enabled field to the opposite of the current value right? Like if the current state is false, then change to true and vice-versa? Commented Dec 31, 2022 at 0:39
  • Yes if its true it will become false if it is false it will become true Commented Dec 31, 2022 at 0:40

2 Answers 2

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) {})
Sign up to request clarification or add additional context in comments.

2 Comments

If there is a document in the collection that doesn't have an enabled field, or has an enabled field with a non-boolean value, what should happen?
That wont be the case thank you a lot for the help
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) {})

3 Comments

Is it possible to do this with a boolean ? I cannot tranisition the entire DB to use integers
I made an update to the answer
I tried it but I got this weird result: enabled: { '$expr': [Object] }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.