mongodbmongodb-querybitwise-xor

Using Bitwise OR in MongoDB


I am working on a project where I want to toggle a value between 0 and 1 within my Mongo Database. I have set every value from the default double to a 32 bit Int. However, every time I run this code, I get this error:

> db.players.update({name: "Patrick Mahomes"}, {$bit: {active: {xor:1}}})
WriteResult({
        "nMatched" : 0,
        "nUpserted" : 0,
        "nModified" : 0,
        "writeError" : {
                "code" : 2,
                "errmsg" : "The $bit modifier field must be an Integer(32/64 bit); a 
'double' is not supported here: {xor: 1.0}"
        }

Any idea why this is occurring? When I query the active field type, it returns all of the objects in my database.

> db.players.find({active: {$type:16}})

This will end up being the functionality behind a button click on a website to toggle between two different states.


Solution

  • Numbers passed in the mongo shell are deduced to be double to match javascript-style conventions. So the 1 in {xor: 1} is a double.

    You'll need to specify NumberInt(1) to get a 32-bit integer (or NumberLong(1) for a 64-bit integer).

    This behavior is documented here