Mongodb Data Types
MongoDB is a NoSQL database that supports various data types for storing data in documents. Each field in a MongoDB document can have a specific data type. Here’s an overview of the commonly used data types in MongoDB:
1. String
- Used to store textual data.
- Example:
"name": "John Doe"
2. Number
MongoDB provides two number types:
- Integer: 32-bit or 64-bit integers, depending on your platform.
- Example:
"age": 30
- Example:
- Double: For floating-point values.
- Example:
"price": 19.99
- Example:
3. Boolean
- Used to store
true
orfalse
values. - Example:
"isActive": true
4. Date
- Stores dates and times as ISO 8601 format.
- Example:
"createdAt": ISODate("2024-12-14T00:00:00Z")
5. Array
- Used to store a list of values.
- Example:
"tags": ["mongodb", "database", "nosql"]
6. Object (Embedded Document)
- Stores a nested document (key-value pairs within another document).
- Example:
7. ObjectId
- A 12-byte unique identifier for documents created automatically unless specified.
- Example:
"id": ObjectId("507f1f77bcf86cd799439011")
8. Binary Data
- Stores binary data like images or files.
- Example:
"file": BinData(0, "binaryContentInBase64")
9. Null
- Represents a
null
value or an empty field. - Example:
"middleName": null
10. Regular Expression
- Stores regex patterns.
- Example:
"pattern": /mongodb/i
11. JavaScript Code
- Used to store JavaScript code snippets.
- Example:
"script": function() { return this.name; }
12. Decimal128
- A high-precision 128-bit decimal type, useful for financial and monetary data.
- Example:
"salary": NumberDecimal("12345.67")
13. MinKey
- Represents the smallest value for sorting and comparison.
- Used internally for specific queries.
- Example:
"key": MinKey
14. MaxKey
- Represents the largest value for sorting and comparison.
- Example:
"key": MaxKey
15. Timestamp
- Special internal type for storing timestamps, primarily used by MongoDB’s replication system.
- Example:
"updatedAt": Timestamp(1609459200, 1)
16. Undefined
- Represents an undefined value (deprecated in favor of
null
). - Example:
"optionalField": undefined
These data types provide flexibility and efficiency when designing MongoDB schemas, allowing developers to handle various types of data easily.