Search code examples
javascriptmongodbmongoose

Which takes less memory in MongoDB, a number or a string?


I'm trying to make my database as efficient as possible. It's a really simple database in which the collections only have documents that store either strings, or numbers or booleans. No arrays, mixed data types etc. If I want to store 24 as the value of one of the fields (which will only contain natural numbers). Which would take less space

{
 field: 24
}

or

{
 field: "24"
}

I'm using mongoose, and what I'm basically asking is that should I set Number or String as the type in my Schema for that particular field.


Solution

  • Store numbers as Numbers.

    MongoDB uses BSON (spec). Number in this context usually means a 64-bit IEEE-754 floating-point number (what BSON calls a double), so that's going to take...64 bits. :-) Add to that the overhead (according to the spec) of saying it's a number (one byte) and the field name (the length of the name plus one byte), but as those will be the same for Number and String we can disregard them. So 64 bits for Number.

    The spec says String is stored as a 32-bit length followed by the string in UTF-8 followed by a terminator byte (plus the overhead in common with Number). That's 32 + (8 x number_of_bytes_in_utf_8) + 8 bits for a string.

    Each of the characters used to represent numbers in strings (-, +, 0-9, e/E [for scientific notation], and .) are represented with a single byte in UTF-8, so for our purposes in this question, # of chars = # of bytes.

    So:

    • For "24" it's 32 + (8 x 2) + 8 giving us 56 bits.
    • For "254" it's 32 + (8 x 3) + 8 giving us 64 bits.
    • For "2254" it's 32 + (8 x 4) + 8 giving us 72 bits.
    • For "1.334" it's 32 + (8 x 5) + 8 giving us 80 bits.

    See where I'm going with this? :-)

    Add to that the fact that if it's a number, then storing it as a string:

    ...and I'd say Number is your clear choice.