TIL: Understanding Memory Usage of Numbers and Strings in MongoDB

In MongoDB, the memory size of data types like Number and String varies depending on the specific type and content. Here’s a simplified breakdown:

Number Data Types:

  • Double (64-bit floating-point): 8 bytes.
  • 32-bit Integer (int): 4 bytes.
  • 64-bit Integer (long): 8 bytes.
  • Decimal128 (high-precision): 16 bytes.

String Data Type:

  • Memory Size: Depends on the length of the string in UTF-8 encoding.
  • Formula: (Number of UTF-8 characters) + 1 byte for a null terminator + 4 bytes for overhead.

For example, the string “hello” would require 10 bytes in total.

Takeaway:

  • Numbers have fixed sizes, while Strings vary based on length.
  • Efficient memory usage in MongoDB starts with understanding the data types you’re working with.