This guide covers fundamental MongoDB interview questions that are commonly asked in technical interviews. Each question includes a detailed answer and relevant code examples.
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents. It's designed for scalability, performance, and developer productivity.
MongoDB consists of several key components:
A document in MongoDB is a data structure composed of field and value pairs. Documents are similar to JSON objects but use BSON format.
// Example Document
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "John Doe",
"age": 30,
"email": "john@example.com",
"address": {
"street": "123 Main St",
"city": "New York",
"zip": "10001"
},
"hobbies": ["reading", "gaming", "coding"]
}
A collection is a group of MongoDB documents, similar to a table in relational databases. Collections don't enforce a schema, allowing documents within a collection to have different fields.
// Creating a collection
db.createCollection("users")
// Inserting documents into collection
db.users.insertOne({
name: "John Doe",
email: "john@example.com"
})
// Viewing collection documents
db.users.find()
MongoDB | SQL Databases |
---|---|
Document-oriented | Table-oriented |
Dynamic schema | Fixed schema |
Horizontal scaling | Vertical scaling |
JSON-like documents | Rows and columns |
No joins required | Uses joins |
The _id field is a unique identifier for each document in a MongoDB collection. It has the following characteristics:
// Example of _id field
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "John Doe"
}
// Custom _id
{
"_id": "user123",
"name": "John Doe"
}
NoSQL databases are categorized into four main types:
MongoDB is a document database that stores data in BSON format, offering flexibility and scalability for modern applications.
BSON (Binary JSON) is a binary-encoded serialization of JSON-like documents used by MongoDB. It provides:
// JSON
{
"name": "John",
"age": 30,
"date": "2023-01-01"
}
// BSON (conceptual)
{
"name": "John",
"age": 30,
"date": ISODate("2023-01-01")
}
Continue your MongoDB interview preparation with: