0% completed
In MongoDB, data is stored in BSON format, which supports a variety of data types. Each data type plays a crucial role in how data is stored, queried, and manipulated.
This lesson will provide an in-depth explanation of each BSON data type used in MongoDB, along with examples to illustrate their usage.
Here is a detailed explanation of each BSON data type with examples:
In each example, we used the insertOne()
method to insert the data into the current database. It takes the JSON object as a parameter. We will learn it in the next chapter.
String
db.myCollection.insertOne({ name: "John Doe" })
Integer
db.myCollection.insertOne({ age: 30 })
Double
db.myCollection.insertOne({ price: 19.99 })
Boolean
true
or false
.db.myCollection.insertOne({ isStudent: false })
Null
db.myCollection.insertOne({ middleName: null })
Array
db.myCollection.insertOne({ tags: ["mongodb", "database", "NoSQL"] })
Object
db.myCollection.insertOne({ address: { street: "123 Main St", city: "Anytown", zipcode: "12345" } })
Binary Data
db.myCollection.insertOne({ fileData: new BinData(0, "binarydatahere") })
ObjectId
_id
field of type ObjectId if none is provided.db.myCollection.insertOne({ _id: ObjectId("507f1f77bcf86cd799439011") })
Date
db.myCollection.insertOne({ createdAt: new Date() })
Regular Expression
db.myCollection.insertOne({ pattern: /abc/i })
JavaScript
db.myCollection.insertOne({ code: function() { return "Hello, MongoDB!"; } })
JavaScript with Scope
db.myCollection.insertOne({ codeWithScope: { $code: "function() { return x; }", $scope: { x: 1 } } })
Timestamp
db.myCollection.insertOne({ timestamp: Timestamp() })
Decimal128
db.myCollection.insertOne({ bigNumber: NumberDecimal("12345.6789") })
Min Key and Max Key
MinKey
is the lowest possible value and MaxKey
is the highest possible value.db.myCollection.insertOne({ minKeyField: MinKey(), maxKeyField: MaxKey() })
Understanding the various BSON data types in MongoDB is essential for effectively storing and manipulating data. Each data type has specific characteristics and use cases that can significantly impact the performance and functionality of your database. By leveraging the appropriate data types, you can ensure that your MongoDB applications are both efficient and capable of handling a wide range of data structures.
.....
.....
.....