mongodb string less space than float
is it true th开发者_开发百科at in mongodb saving strings take up less space than floats?
so if I have an updated time field, rather than saving the time as a float I should save it as a string?
Are there any reasons why I would not want to do that?
Thanks.
No, it's not true. Floating point numbers are stored using eight bytes, so regardless of the size of the number it will always be eight bytes. Strings are variable length, so a string representation of a number will take up as many bytes as required.
However, that does not mean that you can save space by using strings when the string representation is shorter than eight chars. There is also an overhead in the form of the length of the string and a null terminator, i.e. five bytes. "2.1"
requires fewer bytes to represent than the number 2.1
, but as soon as you get over five chars the string will require more space. If you save your numbers as four byte integers no string representation can be smaller.
This can be seen by entering the following commands into a mongo
shell:
> Object.bsonsize({a: 2.1})
16
> Object.bsonsize({a: "2.1"})
16
> Object.bsonsize({a: 2.11})
16
> Object.bsonsize({a: "2.11"})
17
2.1
and "2.1"
are the same size, because the string is three chars long, plus an overhead of three bytes, making it the same size as the eight byte float (the other eight bytes are overhead for the object and key). Changing the number to 2.11
does not change the size, but "2.11"
is one byte bigger.
You can find the exact byte sizes of different data types of the BSON format in the specification: http://bsonspec.org/#/specification
If you really care about space, and store something simple (with only a few decimal fraction digits, limited range) you can multiply that with 10, 100, ... and store it as an int32.
精彩评论