Binary (Binary Data)
Last updated: 2026-10-09
Binary (Binary Data)
Binary stores images, files, encrypted data, and UUIDs — more compact than Base64 strings, with subtypes (0 generic, 2 old binary, 3 UUID legacy, 4 UUID, 7 encrypted). Store directly within the 16MB document limit; use GridFS for larger files. In mongosh construct with `BinData(subtype, 'base64')` or `Binary.createFromBase64('...')`.
| Category | BSON Types |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
BinData(<subtype>, "<base64>")
UUID("<uuid string>")
Binary.createFromBase64("<base64>")
Returns:Returns a Binary BSON value
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// Binary: store binary data
use shop
db.files.insertOne({ name: 'logo.png', data: BinData(0, 'iVBORw0KGgo=') })
Output:
{ _id: ObjectId('...'), name: 'logo.png', data: Binary.createFromBase64('iVBORw0KGgo=') }
📌 Notes
- Large files belong in GridFS, not documents (16MB cap)
- Store UUIDs as subtype 4 for cross-driver consistency
- Base64 strings cost ~33% more space than Binary
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QCan I store images directly in MongoDB?
AUnder 16MB, yes — use a Binary field; beyond that, use GridFS or object storage.
QHow is a UUID stored in MongoDB?
AAs Binary subtype 4 (UUID); drivers convert automatically.
QBinary or Base64 string?
AUse Binary for binary data (compact, subtypes); String for text.