Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I store boolean values in mongodb?

Tags:

I see three main possibilities for storing boolean information in mongodb:

  1. 0 or 1 as a String
  2. 0 or 1 as a Number
  3. True or False as a Boolean

What are the advantages/disadvantages of each method in terms of storage space used and the speed of queries?

like image 484
Chris Paterson Avatar asked Dec 08 '14 03:12

Chris Paterson


People also ask

How do you store Boolean values?

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”.

Can Boolean data be stored?

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.


1 Answers

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.

like image 141
Stennie Avatar answered Sep 20 '22 15:09

Stennie