0
0
MongoDBquery~5 mins

BSON data types overview in MongoDB

Choose your learning style9 modes available
Introduction

BSON data types help MongoDB store and organize different kinds of information clearly and efficiently.

When you want to save numbers, text, or dates in a MongoDB database.
When you need to store complex data like lists or nested objects.
When you want to keep track of true/false values in your data.
When you need to store special data like binary files or unique IDs.
When you want to ensure your data is stored in a way MongoDB understands.
Syntax
MongoDB
BSON data types include:
- String
- Integer
- Double
- Boolean
- Date
- Array
- Object
- ObjectId
- Binary Data
- Null
- Regular Expression
- Timestamp
- Decimal128
- MinKey
- MaxKey
BSON stands for Binary JSON, a format MongoDB uses to store data.
Each data type helps MongoDB know how to handle and search your data.
Examples
A simple document with String, Integer, and Boolean types.
MongoDB
{ name: "Alice", age: 30, active: true }
Shows an Array of Integers and a Date type.
MongoDB
{ scores: [85, 90, 78], joined: ISODate("2023-01-01T00:00:00Z") }
Uses ObjectId for unique ID and Binary Data for storing files.
MongoDB
{ _id: ObjectId("507f1f77bcf86cd799439011"), data: BinData(0, "...base64...") }
Sample Program

This example inserts a user document with various BSON types and then retrieves it.

MongoDB
db.users.insertOne({
  _id: ObjectId("507f1f77bcf86cd799439011"),
  name: "Bob",
  age: 25,
  active: true,
  scores: [88, 92, 79],
  joined: ISODate("2024-01-15T10:00:00Z"),
  profilePic: BinData(0, "VGhpcyBpcyBhIHRlc3Q=")
})

// Then find the document
 db.users.find({ name: "Bob" })
OutputSuccess
Important Notes

BSON types allow MongoDB to store data efficiently and support rich queries.

Using the right data type helps keep your data organized and easy to work with.

ObjectId is a special type used as a unique identifier for documents.

Summary

BSON data types define how MongoDB stores different kinds of data.

Common types include String, Integer, Boolean, Date, Array, and ObjectId.

Choosing the correct type helps MongoDB manage and query your data well.