MongoDB is a NoSQL document database that stores data in flexible, JSON-like documents. Understanding the different data types available in MongoDB is crucial for effective schema design and efficient querying. This tutorial will cover all the fundamental data types supported by MongoDB, along with real-world examples and best practices.
MongoDB supports a wide range of data types, which can be categorized into the following groups:
_id field.Strings in MongoDB are UTF-8 encoded text. They are used to store textual data and can include any character from the Unicode character set.
// Example of a string in MongoDB
db.collection.insertOne({ name: "Alice" });
MongoDB supports two types of numbers:
NumberInt.NumberLong.For floating-point numbers, MongoDB uses the standard JavaScript number type.
// Example of different number types in MongoDB
db.collection.insertOne({
age: NumberInt(25),
salary: NumberLong(100000),
height: 5.9 // Floating-point number
});
Booleans represent true or false values.
// Example of a boolean in MongoDB
db.collection.insertOne({ isActive: true });
MongoDB supports null values, which are used to indicate the absence of a value. The undefined type is not stored in documents but can be used in queries.
// Example of null in MongoDB
db.collection.insertOne({ status: null });
Arrays allow storing an ordered list of values. Each element in an array can be of any data type, including other arrays or objects.
// Example of an array in MongoDB
db.collection.insertOne({
tags: ["mongodb", "database", "noSQL"],
scores: [85, 90, 78]
});
Documents are the core unit of data storage in MongoDB. They are similar to JSON objects and can contain nested documents and arrays.
// Example of a document in MongoDB
db.collection.insertOne({
name: "Bob",
address: {
street: "123 Main St",
city: "Anytown"
},
hobbies: ["reading", "hiking"]
});
Binary data is used to store binary files such as images, PDFs, or any other type of file. MongoDB provides the BinData function to handle binary data.
// Example of binary data in MongoDB
const imageBuffer = fs.readFileSync("path/to/image.jpg");
db.collection.insertOne({ profilePicture: BinData(0, imageBuffer.toString("base64")) });
MongoDB uses the JavaScript Date object to represent specific points in time. Dates are stored as 64-bit integers representing milliseconds since the Unix epoch.
// Example of a date in MongoDB
db.collection.insertOne({ createdAt: new Date() });
ObjectIDs are unique identifiers for documents. They are automatically generated by MongoDB when a document is inserted into a collection, unless explicitly specified.
// Example of an ObjectID in MongoDB
const ObjectId = require("mongodb").ObjectId;
db.collection.insertOne({ _id: new ObjectId(), name: "Charlie" });
Regular expressions are used for pattern matching. They can be used in queries to search for documents that match a specific pattern.
// Example of a regular expression in MongoDB
db.collection.find({ name: { $regex: /^A/ } }); // Finds all names starting with 'A'
MongoDB supports storing and executing JavaScript code. This can be useful for server-side scripting or custom aggregation operations.
// Example of a JavaScript code in MongoDB
db.collection.insertOne({
script: new Code("function() { return 'Hello, World!'; }")
});
undefined values are not stored, avoid using them in your documents unless necessary.Understanding the data types available in MongoDB is essential for designing efficient and effective databases. By leveraging the right data types and best practices, you can optimize your MongoDB applications for better performance and scalability.