MongoDB
MongoDB is a popular open-source, NoSQL database management system known
for its flexibility, scalability, and ease of use. It belongs to the document-oriented
database category, meaning it stores data in a format similar to JSON (JavaScript
Object Notation) documents. Here's a brief overview of MongoDB's key features
and concepts:
1. Document-Oriented: MongoDB stores data in flexible, JSON-like documents,
making it easy to store and represent complex data structures. These
documents can vary in structure and can contain arrays and other nested
documents.
2. Schema-less Design: Unlike traditional relational databases, MongoDB
doesn't require a predefined schema for the data it stores. This provides
flexibility as fields can be added or removed from documents without
affecting other documents in the collection.
3. High Scalability: MongoDB is designed to scale horizontally, meaning it can
handle large volumes of data by distributing it across multiple servers. This
allows for high performance and scalability as the database grows.
4. Querying: MongoDB supports a powerful query language that allows for
complex queries using a variety of operators and expressions. It also
supports indexing for efficient querying of large datasets.
5. Aggregation Framework: MongoDB provides an aggregation framework that
allows for data processing and analysis within the database itself. It supports
a variety of operations such as filtering, grouping, sorting, and more.
6. Replication and High Availability: MongoDB supports replication, allowing
data to be replicated across multiple servers for fault tolerance and high
availability. It also provides automatic failover and data redundancy features
to ensure data availability in case of server failures.
7. Sharding: MongoDB supports sharding, which involves partitioning data
across multiple servers to distribute the load and improve scalability. This
allows MongoDB to handle large datasets and high write throughput.
8. Community and Ecosystem: MongoDB has a large and active community,
providing resources, tutorials, and support for users. It also has a rich
ecosystem with libraries, frameworks, and tools for integration with various
programming languages and platforms.
Overall, MongoDB is well-suited for a wide range of applications, including web,
mobile, IoT, and big data, where flexibility, scalability, and performance are key
requirements.
In MongoDB, a database is created implicitly when you first create a collection within
that database. MongoDB does not require you to explicitly create a database before
using it. When you insert data into a collection within a database that doesn't exist yet,
MongoDB automatically creates the database and the collection.
However, if you want to explicitly create a new database, you can use the use command
followed by the name of the database you want to create. Here's how you can do it
using the MongoDB shell:
use my_database
Replace my_database with the name you want to give to your database. If the database
already exists, MongoDB will switch to that database. If the database doesn't exist,
MongoDB will create it.
It's important to note that until you create at least one document within a collection in
the database, the database itself won't be visible in the list of databases. This is because
MongoDB creates databases and collections only when they are needed. Once you
insert data into a collection, the database and collection will be visible in the MongoDB
shell or any other MongoDB client.
In MongoDB, you interact with data primarily through collections, which are
analogous to tables in relational databases. Here's a brief overview of how you can
perform basic CRUD (Create, Read, Update, Delete) operations in MongoDB:
1. Inserting Documents: To insert a document into a collection, you can use the
insertOne() or insertMany() methods provided by the MongoDB driver or
client library. Here's an example of inserting a document into a collection
called users:
db.users.insertOne({ name: "John Doe", age: 30, email: "[email protected]"
});
2. Updating Documents: MongoDB provides the updateOne() and
updateMany() methods to update documents in a collection. You can specify
a filter to identify the document(s) to be updated and provide the new values
using update operators. Here's an example of updating a document in the
users collection:
db.users.updateOne( { name: "John Doe" }, { $set: { age: 35 } } );
3. Deleting Documents: To delete documents from a collection, you can use
the deleteOne() or deleteMany() methods. Specify a filter to identify the
document(s) to be deleted. Here's an example of deleting a document from
the users collection:
db.users.deleteOne({ name: "John Doe" });
4. Querying Documents: MongoDB provides the find() method to query
documents in a collection. You can specify a filter to retrieve documents that
match certain criteria. Here's an example of querying documents from the
users collection:
// Find all documents
db.users.find();
// Find documents with a specific condition
db.users.find({ age: { $gte: 30 } });
// Find documents with projection (return only specific fields)
db.users.find({}, { name: 1, age: 1 });
These are the basic operations for interacting with MongoDB collections. MongoDB
offers many more advanced features for querying, indexing, aggregation, and
more, allowing for powerful and flexible data manipulation.
Here are 20 different queries to retrieve documents from a collection containing
sample employee documents:
1. Retrieve all documents:
db.employees.find({});
2. Retrieve documents where salary is greater than 50000:
db.employees.find({ salary: { $gt: 50000 } });
3. Retrieve documents where phone number starts with "555":
db.employees.find({ phone: /^555/ });
4. Retrieve documents where email ends with "@example.com":
db.employees.find({ email: /@example\.com$/ });
5. Retrieve documents where department is "IT":
db.employees.find({ department: "IT" });
6. Retrieve documents hired after a specific date:
db.employees.find({ hiredate: { $gt: ISODate("2022-01-01") } });
7. Retrieve documents with a specific name:
db.employees.find({ name: "John Doe" });
8. Retrieve documents where salary is between 40000 and 60000:
db.employees.find({ salary: { $gte: 40000, $lte: 60000 } });
9. Retrieve documents where phone number is not null:
db.employees.find({ phone: { $exists: true } });
10.Retrieve documents where email is not provided:
db.employees.find({ email: { $exists: false } });
11.Retrieve documents where hire date is within a specific range:
db.employees.find({ hiredate: { $gte: ISODate("2022-01-01"), $lte: ISODate("2022-
12-31") } });
12.Retrieve documents where department is either "IT" or "HR":
db.employees.find({ department: { $in: ["IT", "HR"] } });
13.Retrieve documents where salary is not equal to 60000:
db.employees.find({ salary: { $ne: 60000 } });
14.Retrieve documents where phone number is provided and email is not:
db.employees.find({ phone: { $exists: true }, email: { $exists: false } });
15.Retrieve documents where name contains "Doe":
db.employees.find({ name: /Doe/ });
16.Retrieve documents where hire date is within the last 3 months:
db.employees.find({ hiredate: { $gte: new Date(Date.now() - 90 * 24 * 60 * 60 *
1000) } });
17.Retrieve documents sorted by salary in descending order:
db.employees.find().sort({ salary: -1 });
18.Retrieve documents with pagination (skip 10 documents and limit to 5):
db.employees.find().skip(10).limit(5);
19.Retrieve documents where salary is greater than 50000 and department is
"IT":
db.employees.find({ salary: { $gt: 50000 }, department: "IT" });
20.Retrieve documents where email is provided and hire date is within the last
year:
db.employees.find({ email: { $exists: true }, hiredate: { $gte: new Date(Date.now()
- 365 * 24 * 60 * 60 * 1000) } });
Here are some MongoDB queries with group functions:
1. Grouping by Department and Calculating Average Salary:
db.employees.aggregate([ { $group: { _id: "$department", averageSalary: { $avg:
"$salary" } } } ]);
2. Counting Number of Employees in Each Department:
db.employees.aggregate([ { $group: { _id: "$department", count: { $sum: 1 } } } ]);
3. Finding Maximum Salary in Each Department:
db.employees.aggregate([ { $group: { _id: "$department", maxSalary: { $max:
"$salary" } } } ]);
4. Calculating Total Salary Expense for Each Department:
db.employees.aggregate([ { $group: { _id: "$department", totalSalary: { $sum:
"$salary" } } } ]);
5. Finding the Oldest Employee in Each Department (based on hire date):
db.employees.aggregate([ { $group: { _id: "$department", oldestEmployee: { $min:
"$hiredate" } } } ]);
6. Grouping by Department and Sorting by Average Salary:
db.employees.aggregate([ { $group: { _id: "$department", averageSalary: { $avg:
"$salary" } } }, { $sort: { averageSalary: -1 } } ]);
7. Calculating Salary Range for Each Department (difference between max and
min salary):
db.employees.aggregate([ { $group: { _id: "$department", minSalary: { $min:
"$salary" }, maxSalary: { $max: "$salary" } } }, { $project: { _id: 1, salaryRange: {
$subtract: ["$maxSalary", "$minSalary"] } } } ]);
8. Grouping by Department and Finding the Top 3 Highest Paid Employees in
Each Department:
db.employees.aggregate([ { $sort: { salary: -1 } }, { $group: { _id: "$department",
employees: { $push: { name: "$name", salary: "$salary" } } } }, { $project: { _id: 1,
top3Employees: { $slice: ["$employees", 3] } } } ]);
Here are 30 multiple-choice questions (MCQs) along with their answers based on
the details provided about MongoDB:
Which of the following best describes MongoDB?
a) A relational database management system
b) A document-oriented NoSQL database
c) A graph database
d) A key-value store
Answer: b) A document-oriented NoSQL database
MongoDB is known for its flexibility primarily because:
a) It enforces a strict schema for data storage
b) It allows only predefined data structures
c) It stores data in JSON-like documents
d) It doesn't support querying
Answer: c) It stores data in JSON-like documents
Which method is used to insert a single document into a MongoDB collection?
a) insertOne()
b) insert()
c) addOne()
d) create()
Answer: a) insertOne()
MongoDB supports which type of scaling?
a) Vertical scaling
b) Horizontal scaling
c) Diagonal scaling
d) Linear scaling
Answer: b) Horizontal scaling
What query operator is used to specify a greater than condition in MongoDB?
a) $gt
b) $lt
c) $gte
d) $lte
Answer: a) $gt
Which aggregation function is used to calculate the average of a numeric field in
MongoDB?
a) $avg
b) $sum
c) $max
d) $min
Answer: a) $avg
MongoDB uses which method to update documents in a collection?
a) updateOne()
b) modify()
c) change()
d) replaceOne()
Answer: a) updateOne()
MongoDB documents are similar to which data format?
a) XML
b) CSV
c) JSON
d) YAML
Answer: c) JSON
Which operator is used for logical AND operation in MongoDB queries?
a) $or
b) $not
c) $and
d) $nor
Answer: c) $and
MongoDB's aggregation framework allows for which of the following operations?
a) Sorting
b) Filtering
c) Grouping
d) All of the above
Answer: d) All of the above
How can you delete multiple documents matching a condition in MongoDB?
a) delete()
b) deleteOne()
c) remove()
d) deleteMany()
Answer: d) deleteMany()
Which query operator is used to perform pattern matching in MongoDB?
a) $in
b) $regex
c) $like
d) $pattern
Answer: b) $regex
MongoDB provides automatic failover and data redundancy features to ensure:
a) Data loss
b) Data integrity
c) Data consistency
d) Data compression
Answer: b) Data integrity
Which method is used to retrieve a single document from a MongoDB collection?
a) findOne()
b) getOne()
c) fetchOne()
d) retrieveOne()
Answer: a) findOne()
What does MongoDB use to distribute data across multiple servers for scalability?
a) Replication
b) Sharding
c) Clustering
d) Partitioning
Answer: b) Sharding
Which query operator is used to specify a less than or equal to condition in
MongoDB?
a) $gt
b) $lt
c) $gte
d) $lte
Answer: d) $lte
MongoDB's schema-less design means:
a) It enforces a strict schema for data storage
b) It requires a predefined schema for data storage
c) It doesn't require a predefined schema for data storage
d) It only supports fixed-size schemas
Answer: c) It doesn't require a predefined schema for data storage
MongoDB provides the aggregate() method to perform:
a) Data insertion
b) Data updating
c) Data querying
d) Data aggregation
Answer: d) Data aggregation
Which method is used to delete a single document from a MongoDB collection?
a) deleteOne()
b) removeOne()
c) eraseOne()
d) destroyOne()
Answer: a) deleteOne()
MongoDB supports which type of database indexing?
a) Primary indexing
b) Secondary indexing
c) Tertiary indexing
d) Quaternary indexing
Answer: b) Secondary indexing
How can you update multiple documents matching a condition in MongoDB?
a) update()
b) updateMany()
c) modifyMany()
d) changeMany()
Answer: b) updateMany()
Which of the following is true about MongoDB's replication?
a) It doesn't support replication
b) It provides automatic failover
c) It requires manual intervention for failover
d) It doesn't ensure data redundancy
Answer: b) It provides automatic failover
MongoDB's $exists operator is used to check for the existence of:
a) Collections
b) Documents
c) Fields
d) Databases
Answer: c) Fields
Which method is used to retrieve all documents from a MongoDB collection?
a) fetchAll()
b) retrieveAll()
c) find()
d) getAll()
Answer: c) find()
MongoDB's sharding is used for:
a) Vertical scaling
b) Horizontal scaling
c) Diagonal scaling
d) Linear scaling
Answer: b) Horizontal scaling
The $project stage in MongoDB aggregation pipeline is used for:
a) Sorting
b) Filtering
c) Projecting fields
d) Grouping
Answer: c) Projecting fields
MongoDB's $ne operator is used to specify:
a) Equal to condition
b) Not equal to condition
c) Greater than condition
d) Less than condition
Answer: b) Not equal to condition
Which method is used to delete all documents from a MongoDB collection?
a) remove()
b) deleteAll()
c) deleteMany()
d) deleteAllDocuments()
Answer: c) deleteMany()
MongoDB's aggregation framework is based on which concept?
a) SQL
b) MapReduce
c) Joins
d) Transactions
Answer: b) MapReduce
MongoDB's $slice operator is used for:
a) Sorting
b) Filtering
c) Limiting array elements
d) Grouping
Answer: c) Limiting array elements