I see three main possibilities for storing boolean information in mongodb:
What are the advantages/disadvantages of each method in terms of storage space used and the speed of queries?
Boolean values are not actually stored in Boolean variables as the words “true” or “false”. Instead, they are stored as integers: true becomes the integer 1, and false becomes the integer 0. Similarly, when Boolean values are evaluated, they don't actually evaluate to “true” or “false”.
Boolean data types can be used to store the values true and false in a database. Booleans are most commonly used in databases to represent yes/no, on/off, or other related states.
Boolean
is a native field type in BSON (MongoDB's server-side storage format, aka "Binary JSON"). Booleans use less storage than an integer or string and avoid any unexpected side effects of comparison.
For example, in a MongoDB find()
query a string of "1"
will not match a numeric value of 1
or a boolean value of true
. If you want to store boolean values, definitely use a boolean type.
Comparing the BSON size (in bytes) in the mongo
shell for completeness:
// Number (JavaScript double) - 8 bytes > var foo = { a: 1 } > Object.bsonsize(foo) 16 // UTF-8 String - 6 bytes > var foo = { a: '1'} > Object.bsonsize(foo) 14 // 32-bit int - 4 bytes > var foo = { a: NumberInt(1)} > Object.bsonsize(foo) 12 // Boolean - 1 byte > var foo = { a: true} > Object.bsonsize(foo) 9
Note: the base size of the JSON object in the examples above (not counting the field values) is 8 bytes, so the difference between the reported Object.bsonsize()
is the representation of the field value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With