Lecture Notes Of Class 12: Introduction to
MongoDB
Objective:
- To
understand MongoDB and its significance as a NoSQL database.
- To
learn how to use MongoDB with Node.js for database operations.
What is MongoDB?
MongoDB is a NoSQL
database that stores data in a flexible, JSON-like format known as BSON
(Binary JSON). Unlike traditional relational databases (like MySQL),
MongoDB does not rely on tables and rows but instead uses collections
and documents.
Key Features:
1.
Schema-less Database:
Flexible structure, allowing different fields in different documents of the
same collection.
2.
Scalability:
Easily scalable horizontally by adding more servers.
3.
High Performance:
Optimized for large-scale applications.
4.
Rich Query Language:
Supports a wide range of queries, including filtering, aggregation, and
indexing.
5.
Cross-Platform:
Works on multiple operating systems like Windows, Linux, and macOS.
MongoDB Terminology
1.
Database:
A container for collections.
2.
Collection:
Equivalent to a table in relational databases.
3.
Document:
A record in a collection, represented in BSON.
4.
Field:
A key-value pair in a document, similar to a column in a table.
Example of a Document:
json
CopyEdit
{
"name": "John Doe",
"age": 25,
"skills": ["JavaScript", "Node.js",
"MongoDB"]
}
How MongoDB Differs from
SQL Databases
|
Feature |
SQL Databases |
MongoDB |
|
Structure |
Tables and Rows |
Collections and
Documents |
|
Schema |
Fixed schema |
Flexible schema |
|
Scalability |
Vertical |
Horizontal |
|
Query Language |
SQL |
MongoDB Query Language
(MQL) |
Using MongoDB with
Node.js
Step 1: Install and Set
Up MongoDB
Option 1: Install MongoDB
Locally
1.
Download MongoDB Community Server from MongoDB
Download Center.
2.
Install MongoDB and start the MongoDB
server using the following command:
bash
CopyEdit
mongod
3.
Use the MongoDB shell to interact with the
database:
bash
CopyEdit
mongo
Option 2: Use MongoDB
Atlas (Cloud-Based Solution)
1.
Sign up at MongoDB Atlas.
2.
Create a cluster and get the connection
string (e.g., mongodb+srv://<username>:<password>@cluster.mongodb.net/<dbname>).
Step 2: Install the
Mongoose Package
Mongoose is an ODM
(Object Data Modeling) library for MongoDB and Node.js that provides a
structured way to interact with MongoDB.
1.
Open your Node.js project directory and
install Mongoose:
bash
CopyEdit
npm install mongoose
Step 3: Connect Node.js
to MongoDB
1.
Create a New File:
index.js.
2.
Import and Connect Mongoose:
javascript
CopyEdit
const mongoose = require('mongoose');
// MongoDB connection
string (replace `<username>`, `<password>`, and `<dbname>`
with your details)
const uri = "mongodb+srv://<username>:<password>@cluster.mongodb.net/<dbname>";
mongoose.connect(uri, { useNewUrlParser:
true, useUnifiedTopology: true })
.then(() => console.log("MongoDB
connected"))
.catch(err => console.log("Error
connecting to MongoDB:", err));
Step 4: Perform Basic
Database Operations
1. Define a Schema and
Model:
A schema defines the structure of a document in MongoDB.
javascript
CopyEdit
const Schema = mongoose.Schema;
// Define schema for a
'User' collection
const userSchema = new Schema({
name: String,
age: Number,
email: String
});
// Create a model
const User = mongoose.model('User',
userSchema);
2. Insert a Document:
javascript
CopyEdit
const newUser = new User({
name: "Alice",
age: 30,
email: "alice@example.com"
});
newUser.save()
.then(() => console.log("User
added!"))
.catch(err => console.log("Error:",
err));
3. Retrieve Documents:
javascript
CopyEdit
User.find()
.then(users => console.log("All
Users:", users))
.catch(err => console.log("Error:",
err));
4. Update a Document:
javascript
CopyEdit
User.updateOne({ name: "Alice"
}, { age: 31 })
.then(() => console.log("User
updated!"))
.catch(err => console.log("Error:",
err));
5. Delete a Document:
javascript
CopyEdit
User.deleteOne({ name: "Alice"
})
.then(() => console.log("User
deleted!"))
.catch(err => console.log("Error:",
err));
Lab Tasks
1.
Install MongoDB:
Either locally or via MongoDB Atlas.
2.
Install Mongoose:
Run npm install mongoose in your project folder.
3.
Connect Node.js to MongoDB:
Use the connection string provided by your MongoDB setup.
4.
Perform Basic Operations:
o Create
a schema and model for a Student collection with fields like name, rollNumber,
and department.
o Insert,
retrieve, update, and delete student records.
Conclusion
In this session, we
learned about:
- MongoDB
as a NoSQL database.
- Installing
and connecting MongoDB with Node.js.
- Using
Mongoose for schema definition and basic CRUD operations.
With these skills, you
can integrate MongoDB into your Node.js projects to build robust and scalable
applications.
Assignment
1.
Create a new collection called Books with
fields: title, author, and year. Perform CRUD operations on this collection.
2.
Explore MongoDB documentation to learn
about advanced queries.
4o
You said:
Solutions: Create a new
collection called Books with fields: title, author, and year. Perform CRUD
operations on this collection. Explore MongoDB documentation to learn about
advanced queries.
ChatGPT said:
ChatGPT
Solution: CRUD Operations
on Books Collection
Below is a step-by-step
solution for creating and managing a Books collection with fields title, author,
and year.
Step 1: Define Schema and
Model for Books Collection
Create a books.js file or
add the following code to your project:
javascript
CopyEdit
const mongoose = require('mongoose');
// Define the schema for
the Books collection
const bookSchema = new
mongoose.Schema({
title: { type: String, required: true },
author: { type: String, required: true },
year: { type: Number, required: true },
});
// Create the model for
the Books collection
const Book = mongoose.model('Book',
bookSchema);
module.exports = Book;
Step 2: CRUD Operations
Below are examples of
performing Create, Read, Update, and Delete operations.
1. Create a New Book
Add a new book to the Books
collection:
javascript
CopyEdit
const Book = require('./books');
// Import the model
// Create a new book
document
const newBook = new Book({
title: "To Kill a Mockingbird",
author: "Harper Lee",
year: 1960,
});
// Save the document to
the database
newBook.save()
.then(() => console.log("Book added
successfully!"))
.catch(err => console.log("Error
adding book:", err));
2. Read Books
a. Fetch All Books:
Retrieve all documents from the Books collection:
javascript
CopyEdit
Book.find()
.then(books => console.log("All
Books:", books))
.catch(err => console.log("Error
fetching books:", err));
b. Fetch Books by Author:
Retrieve books written by a specific author:
javascript
CopyEdit
Book.find({ author: "Harper
Lee" })
.then(books => console.log("Books by
Harper Lee:", books))
.catch(err => console.log("Error
fetching books:", err));
3. Update a Book
Update the year of a book
by its title:
javascript
CopyEdit
Book.updateOne({ title: "To
Kill a Mockingbird" }, { year: 1961 })
.then(() => console.log("Book updated
successfully!"))
.catch(err => console.log("Error
updating book:", err));
4. Delete a Book
Delete a book by its
title:
javascript
CopyEdit
Book.deleteOne({ title: "To
Kill a Mockingbird" })
.then(() => console.log("Book deleted
successfully!"))
.catch(err => console.log("Error
deleting book:", err));
Advanced MongoDB Queries
1.
Sorting:
Sort books by year in descending order:
javascript
CopyEdit
Book.find().sort({ year:
-1 })
.then(books => console.log("Books
sorted by year:", books))
.catch(err => console.log("Error
sorting books:", err));
2.
Pagination:
Retrieve books in pages (e.g., 5 books per page):
javascript
CopyEdit
const page = 1; //
Current page
const limit = 5; // Books
per page
Book.find()
.skip((page
- 1) * limit)
.limit(limit)
.then(books => console.log("Paginated
books:", books))
.catch(err => console.log("Error
paginating books:", err));
3.
Aggregation:
Count the number of books published per author:
javascript
CopyEdit
Book.aggregate([
{ $group: { _id: "$author", totalBooks:
{ $sum: 1 } } }
])
.then(result => console.log("Books
per author:", result))
.catch(err => console.log("Error
aggregating books:", err));
Exploring MongoDB
Documentation
The MongoDB official
documentation is a rich resource for learning advanced features like indexing,
aggregation pipelines, and geospatial queries.
Visit: MongoDB Documentation
Output Examples
1.
Create:
Output after adding a book:
bash
CopyEdit
Book added successfully!
2.
Read:
Fetch all books:
bash
CopyEdit
All Books: [
{ _id: 1, title: "To Kill a
Mockingbird", author: "Harper Lee", year: 1960 }
]
3.
Update:
Output after updating:
bash
CopyEdit
Book updated
successfully!
4.
Delete:
Output after deletion:
bash
CopyEdit
Book deleted
successfully!
This process helps manage
the Books collection and explore MongoDB's advanced capabilities effectively.
4o
You said:
Write 10 assignments with
solution and explanation in detail on above concept
ChatGPT said:
ChatGPT
10 Assignments on MongoDB
and Node.js
Below are 10 assignments
based on the above concept, each with detailed solutions and explanations to
solidify understanding of MongoDB and Node.js integration.
Assignment 1: Create a
MongoDB Database
Task:
Create a database named Library and verify its existence using MongoDB Compass
or the MongoDB shell.
Solution:
In the MongoDB shell:
bash
CopyEdit
use Library
show dbs
Explanation:
- The
use Library command switches to the Library database, creating it if it
doesn't already exist.
- The
show dbs command lists all databases, including Library if documents are
added.
Assignment 2: Create a
Collection
Task:
Create a collection named Books within the Library database.
Solution:
In the MongoDB shell:
bash
CopyEdit
use Library
db.createCollection("Books")
show collections
Explanation:
- db.createCollection("Books")
explicitly creates the Books collection.
- show
collections lists all collections in the current database.
Assignment 3: Insert a
Document into a Collection
Task:
Add a document with the fields title: "1984", author: "George
Orwell", and year: 1949 into the Books collection.
Solution:
In the MongoDB shell:
bash
CopyEdit
db.Books.insertOne({
title: "1984",
author: "George Orwell",
year: 1949
})
Explanation:
- insertOne
adds a single document to the collection.
- This
creates the Books collection if it doesn’t already exist.
Assignment 4: Retrieve
All Documents from a Collection
Task:
Retrieve all documents from the Books collection.
Solution:
In the MongoDB shell:
bash
CopyEdit
db.Books.find()
Explanation:
- find()
fetches all documents in the Books collection.
- The
output is a JSON-like structure of stored documents.
Assignment 5: Find
Documents with Specific Criteria
Task:
Find all books authored by "George Orwell".
Solution:
In the MongoDB shell:
bash
CopyEdit
db.Books.find({ author: "George
Orwell" })
Explanation:
- The
{ author: "George Orwell" } query filters documents matching the
specified author.
Assignment 6: Update a
Document
Task:
Update the year of the book titled "1984" to 1950.
Solution:
In the MongoDB shell:
bash
CopyEdit
db.Books.updateOne(
{ title: "1984" },
{ $set: { year: 1950 } }
)
Explanation:
- The
$set operator modifies the year field of the matched document.
- updateOne
ensures only the first matching document is updated.
Assignment 7: Delete a
Document
Task:
Delete the book with the title "1984" from the Books collection.
Solution:
In the MongoDB shell:
bash
CopyEdit
db.Books.deleteOne({
title: "1984" })
Explanation:
- deleteOne
removes the first document matching the query.
Assignment 8: Use
Aggregation
Task:
Count the total number of books grouped by author.
Solution:
In the MongoDB shell:
bash
CopyEdit
db.Books.aggregate([
{ $group: { _id: "$author",
totalBooks: { $sum: 1 } } }
])
Explanation:
- $group
groups documents by the author field.
- $sum:
1 counts the number of books per author.
Assignment 9: Pagination
Task:
Retrieve the first two books, sorted by year in descending order.
Solution:
In the MongoDB shell:
bash
CopyEdit
db.Books.find().sort({
year: -1 }).limit(2)
Explanation:
- sort({
year: -1 }) arranges books in descending order of year.
- limit(2)
fetches only the first two documents.
Assignment 10: Integrate
MongoDB with Node.js
Task:
Write a Node.js script to connect to the Library database, create a Books
collection, and insert a new document.
Solution:
In Node.js:
javascript
CopyEdit
const mongoose = require('mongoose');
// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/Library',
{
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => console.log("Connected to
MongoDB"))
.catch(err => console.log("Error
connecting to MongoDB:", err));
// Define schema and
model
const bookSchema = new
mongoose.Schema({
title: String,
author: String,
year: Number,
});
const Book = mongoose.model('Book',
bookSchema);
// Insert a document
const newBook = new Book({
title: "Brave New World",
author: "Aldous Huxley",
year: 1932,
});
newBook.save()
.then(() => console.log("Book added
successfully!"))
.catch(err => console.log("Error
adding book:", err));
Explanation:
1.
mongoose.connect
establishes a connection to the MongoDB database.
2.
Schema and Model:
The schema defines the document structure, while the model interacts with the
collection.
3.
Insert Document:
The save() method adds a new document to the collection.
These assignments guide
students through understanding basic and advanced MongoDB operations and
connecting MongoDB with Node.js. By solving them, students will gain hands-on
experience with CRUD operations, aggregation, and database integration.
4o
You said:
write 50 MCQs for the
concept above with explanation
ChatGPT said:
ChatGPT
50 MCQs on MongoDB and
Node.js
Below are multiple-choice
questions (MCQs) with explanations based on the concepts of MongoDB and
Node.js. Each question tests understanding and practical knowledge.
1. What is MongoDB?
A. A relational database
B. A NoSQL database
C. A flat-file database
D. A cloud-only database
Answer:
B
Explanation: MongoDB is a NoSQL database designed for storing, querying,
and managing document-oriented data.
2. Which data format does
MongoDB use to store data?
A. XML
B. JSON
C. BSON
D. YAML
Answer:
C
Explanation: MongoDB stores data in BSON (Binary JSON), which is a
binary-encoded serialization of JSON-like documents.
3. Which command is used
to switch to a database in MongoDB?
A. use
<database_name>
B. switch <database_name>
C. db <database_name>
D. open <database_name>
Answer:
A
Explanation: The use <database_name> command is used to switch to
a specific database in MongoDB.
4. What is the default
port for MongoDB?
A. 27017
B. 3306
C. 8080
D. 5432
Answer:
A
Explanation: MongoDB uses port 27017 by default for database
connections.
5. In Node.js, which
package is used to interact with MongoDB?
A. mongoose
B. mysql
C. pg
D. sequelize
Answer:
A
Explanation: The mongoose package is commonly used to interact with
MongoDB in Node.js.
6. What does db.createCollection()
do?
A. Deletes a collection
B. Creates a collection explicitly
C. Updates a collection
D. Lists collections
Answer:
B
Explanation: The db.createCollection() command creates a new collection
explicitly.
7. How can you retrieve
all documents in a collection?
A. db.collection.findAll()
B. db.collection.find()
C. db.collection.get()
D. db.collection.select()
Answer:
B
Explanation: The find() method retrieves all documents in a collection.
8. Which method is used
to insert a single document?
A. insert()
B. insertOne()
C. insertDocument()
D. addDocument()
Answer:
B
Explanation: The insertOne() method adds a single document to a
collection.
9. What does mongoose.Schema
do?
A. Connects to MongoDB
B. Defines the structure of a document
C. Creates a new database
D. Deletes a collection
Answer:
B
Explanation: In Mongoose, Schema is used to define the structure and
data types of documents.
10. Which of the
following is a valid Mongoose schema definition?
A. { title: String,
author: String, year: Number }
B. [ title, author, year ]
C. { "title": "String", "author":
"String", "year": "Number" }
D. Schema(title, author, year)
Answer:
A
Explanation: Mongoose schema definitions use JavaScript objects to
specify fields and their types.
11. How do you connect
Node.js to MongoDB using Mongoose?
A. mongoose.connect('mongodb://localhost:27017/dbname')
B. db.connect('localhost:27017/dbname')
C. mongo.connect('localhost:27017/dbname')
D. mongoose.connect('localhost/dbname')
Answer:
A
Explanation: The correct syntax for connecting Node.js to MongoDB is mongoose.connect().
12. What is the output of
db.collection.countDocuments()?
A. Total number of
documents in a collection
B. All document details
C. Document with a specific field
D. Number of collections
Answer:
A
Explanation: The countDocuments() method returns the total number of
documents in a collection.
13. How do you sort
documents in descending order by a field?
A. .sort({ field: 1 })
B. .sort({ field: -1 })
C. .orderBy(field)
D. .desc(field)
Answer:
B
Explanation: Using .sort({ field: -1 }) sorts documents in descending
order based on the specified field.
14. Which of the
following is a MongoDB aggregation pipeline stage?
A. $sort
B. $delete
C. $truncate
D. $update
Answer:
A
Explanation: $sort is an aggregation pipeline stage used to sort
documents.
15. What is the purpose
of the $group stage in MongoDB aggregation?
A. Deletes grouped
documents
B. Groups documents by a field
C. Updates grouped documents
D. Counts grouped documents
Answer:
B
Explanation: $group groups documents based on a specified field and
applies aggregation operations.
16. How do you delete one
document in MongoDB?
A. db.collection.removeOne()
B. db.collection.delete()
C. db.collection.deleteOne()
D. db.collection.remove()
Answer:
C
Explanation: The deleteOne() method removes a single document matching
the query criteria.
17. What is MongoDB
Atlas?
A. A mobile app for
MongoDB
B. A cloud-hosted MongoDB service
C. A command-line tool for MongoDB
D. An offline MongoDB client
Answer:
B
Explanation: MongoDB Atlas is a cloud-hosted database service for
managing MongoDB deployments.
18. What is the purpose
of new mongoose.Schema()?
A. Connects to MongoDB
B. Defines a schema for a collection
C. Deletes a document
D. Updates a document
Answer:
B
Explanation: new mongoose.Schema() is used to define a schema for
documents in a collection.
19. Which operator is
used to update a field in MongoDB?
A. $set
B. $update
C. $change
D. $modify
Answer:
A
Explanation: The $set operator updates the value of a specific field.
20. Which command lists
all databases?
A. show dbs
B. list dbs
C. dbs()
D. display dbs
Answer:
A
Explanation: The show dbs command lists all available databases in
MongoDB.
21. Which of the
following is a NoSQL database type?
A. Document-oriented
B. Relational
C. Tabular
D. Hierarchical
Answer:
A
Explanation: Document-oriented databases, like MongoDB, store data as
documents.
22. How do you check the
current database in MongoDB?
A. current db
B. db.current()
C. db
D. show db
Answer:
C
Explanation: Typing db in the MongoDB shell displays the current
database.
If you'd like the
remaining 28 questions, please let me know, and I'll continue!
4o
You said:
yes
ChatGPT said:
ChatGPT
23. Which method is used
to insert multiple documents into a MongoDB collection?
A. insert()
B. insertMany()
C. bulkInsert()
D. addDocuments()
Answer:
B
Explanation: The insertMany() method is used to insert multiple
documents into a collection at once.
24. What is the primary
advantage of using MongoDB over a relational database?
A. Strong data typing
B. Horizontal scalability
C. Built-in joins
D. Fixed schema
Answer:
B
Explanation: MongoDB's horizontal scalability makes it a popular choice
for handling large datasets.
25. Which method in
Mongoose is used to create a new document?
A. save()
B. add()
C. store()
D. createDocument()
Answer:
A
Explanation: The save() method is used in Mongoose to save a document to
the database.
26. How does MongoDB
handle unstructured data?
A. By enforcing strict
schemas
B. By supporting dynamic schemas
C. By converting to relational format
D. By rejecting unstructured data
Answer:
B
Explanation: MongoDB supports dynamic schemas, allowing it to store
unstructured data.
27. Which of the
following commands shows all collections in a database?
A. list collections
B. show collections
C. db.collections
D. display collections
Answer:
B
Explanation: The show collections command lists all collections in the
current database.
28. What does the findOne()
method return?
A. All documents in a
collection
B. The first document that matches the query
C. The last document that matches the query
D. A count of matching documents
Answer:
B
Explanation: The findOne() method returns the first document that
matches the query criteria.
29. What is a collection
in MongoDB?
A. A single document
B. A group of databases
C. A group of documents
D. A table-like structure with fixed rows
Answer:
C
Explanation: A collection is a group of related documents in MongoDB,
similar to a table in relational databases.
30. Which of the
following is NOT a valid MongoDB data type?
A. String
B. Number
C. Boolean
D. ArrayBuffer
Answer:
D
Explanation: ArrayBuffer is not a valid MongoDB data type. MongoDB
supports types like String, Number, and Boolean.
31. How do you create an
index on a field in MongoDB?
A. db.collection.createIndex({
field: 1 })
B. db.collection.index({ field: 1 })
C. db.collection.addIndex({ field: 1 })
D. db.collection.indexField({ field: 1 })
Answer:
A
Explanation: The createIndex() method creates an index on a specified
field in a collection.
32. What is the purpose
of a primary key in MongoDB?
A. To ensure unique field
values
B. To group related collections
C. To define relationships
D. To allow null values
Answer:
A
Explanation: The _id field in MongoDB acts as the primary key and
ensures each document has a unique identifier.
33. How do you update
multiple documents in MongoDB?
A. updateMany()
B. updateAll()
C. bulkUpdate()
D. updateDocuments()
Answer:
A
Explanation: The updateMany() method is used to update multiple
documents in a collection.
34. What is the purpose
of the $match stage in the aggregation pipeline?
A. To filter documents
based on conditions
B. To delete documents
C. To join collections
D. To create indexes
Answer:
A
Explanation: The $match stage filters documents based on specified
conditions in the aggregation pipeline.
35. Which command is used
to delete a collection in MongoDB?
A. db.collection.deleteCollection()
B. db.collection.remove()
C. db.collection.drop()
D. db.collection.destroy()
Answer:
C
Explanation: The drop() method deletes a collection from the database.
36. What is the purpose
of MongoDB Compass?
A. Command-line tool for
MongoDB
B. Cloud service for hosting databases
C. GUI for managing MongoDB databases
D. Query optimizer
Answer:
C
Explanation: MongoDB Compass is a GUI tool used for managing and
visualizing MongoDB databases.
37. Which method is used
to close a database connection in Node.js?
A. mongoose.close()
B. mongoose.disconnect()
C. db.close()
D. db.disconnect()
Answer:
B
Explanation: The mongoose.disconnect() method is used to close the
database connection.
38. How is the $or
operator used in MongoDB?
A. Filters documents
where at least one condition is true
B. Updates documents where conditions are true
C. Deletes documents matching multiple conditions
D. Joins two collections
Answer:
A
Explanation: The $or operator filters documents where at least one of
the provided conditions is true.
39. How do you define a
unique index in MongoDB?
A. db.collection.createIndex({
field: 1 }, { unique: true })
B. db.collection.addUniqueIndex({ field: 1 })
C. db.collection.setIndex({ field: 1 }, unique)
D. db.collection.uniqueIndex({ field: 1 })
Answer:
A
Explanation: To create a unique index, use createIndex() with the unique:
true option.
40. What does the $push
operator do?
A. Adds a value to an
array field
B. Removes a value from an array
C. Updates a document field
D. Deletes an array field
Answer:
A
Explanation: The $push operator appends a value to an array field in a
document.
41. How do you count the
number of documents in a collection?
A. db.collection.count()
B. db.collection.countDocuments()
C. db.collection.documentCount()
D. db.collection.totalCount()
Answer:
B
Explanation: The countDocuments() method is used to count the number of
documents in a collection.
42. Which Node.js event
is triggered when the MongoDB connection is successful?
A. connected
B. open
C. ready
D. online
Answer:
B
Explanation: The open event is triggered when the MongoDB connection is
successfully established.
43. What is a replica set
in MongoDB?
A. A single database
instance
B. A group of servers for redundancy
C. A way to join collections
D. A command for indexing
Answer:
B
Explanation: A replica set is a group of MongoDB servers that provide
redundancy and high availability.
44. How do you filter
documents where a field value is greater than 100?
A. { field: { $gt: 100 }
}
B. { field: { $gte: 100 } }
C. { field: { $greater: 100 } }
D. { field: { >: 100 } }
Answer:
A
Explanation: The $gt operator filters documents where the field value is
greater than the specified value.
45. What does the $lookup
stage in aggregation do?
A. Deletes documents
B. Joins two collections
C. Updates documents
D. Sorts documents
Answer:
B
Explanation: The $lookup stage performs a join operation between two
collections.
46. How do you delete all
documents in a collection?
A. deleteMany({})
B. deleteAll()
C. removeDocuments()
D. truncate()
Answer:
A
Explanation: The deleteMany({}) method removes all documents from a
collection.
47. What is the default
write concern in MongoDB?
A. majority
B. 1
C. all
D. 0
Answer:
B
Explanation: The default write concern in MongoDB acknowledges the write
operation after the primary node writes the data.
48. What does the _id
field represent in MongoDB?
A. A user-defined primary
key
B. A unique identifier for each document
C. The database name
D. The collection name
Answer:
B
Explanation: The _id field is a unique identifier for every document in
a MongoDB collection.
49. Which operator is
used to check if a field exists in a document?
A. $exists
B. $check
C. $fieldExists
D. $isField
Answer:
A
Explanation: The $exists operator checks if a specified field exists in
a document.

No comments:
Post a Comment