Lecture Notes Of Day 27: MongoDB with Python (PyMongo)

Rashmi Mishra
0

 

Lecture Notes Of Day 27: MongoDB with Python (PyMongo)

Objective:

  • Learn how to use MongoDB in Python applications.
  • Understand how to connect to MongoDB using PyMongo and perform basic database operations like inserting, querying, updating, and deleting data.

Introduction to MongoDB

MongoDB is a NoSQL database that stores data in a flexible, JSON-like format called BSON (Binary JSON). Unlike relational databases, MongoDB does not use tables with rows and columns. Instead, it stores data as documents, which can vary in structure.

MongoDB is widely used in web applications and other systems that need to handle large volumes of unstructured data.

Advantages of MongoDB:

1.   Flexible Schema: You don’t need to define a fixed schema, making it easier to store diverse types of data.

2.   Scalability: MongoDB can scale horizontally to handle large amounts of data across multiple servers.

3.   High Performance: It’s optimized for high performance, especially with read and write operations.

4.   Easy to Use: MongoDB's query language is simple and it is easy to integrate into Python applications.


Introduction to PyMongo

PyMongo is the official Python driver for MongoDB. It allows Python applications to interact with MongoDB databases. Through PyMongo, you can perform various operations such as:

  • Connecting to a MongoDB server.
  • Inserting and retrieving documents.
  • Updating and deleting data.
  • Managing databases and collections.

To begin working with MongoDB in Python, we need to install PyMongo first.


Installation of PyMongo

To install PyMongo, you need to use pip, the Python package manager. Run the following command in your terminal or command prompt:

bash

CopyEdit

pip install pymongo

Once PyMongo is installed, you can start using MongoDB in your Python code.


Establishing a Connection to MongoDB

In order to interact with MongoDB, you first need to establish a connection. This can be done using the MongoClient class from the pymongo module.

Here’s how to connect to a local MongoDB instance:

python

CopyEdit

import pymongo

 

# Connect to the local MongoDB server

client = pymongo.MongoClient("mongodb://localhost:27017/")

 

# Check if the connection is successful

print(client)

If the connection is successful, the client object will give access to all the databases present on the server.


Working with Databases

MongoDB stores data in databases. To work with a specific database, we access it through the client object. If the database doesn’t exist, MongoDB will create it when you first store data.

Creating or Accessing a Database

python

CopyEdit

# Access a specific database

db = client["mydatabase"]

 

# If the database doesn't exist, MongoDB will create it when you insert data

print(db)


Working with Collections

Within a MongoDB database, data is stored in collections (equivalent to tables in relational databases). Each collection contains documents (equivalent to rows in relational databases).

Creating or Accessing a Collection

python

CopyEdit

# Access a collection within the database

collection = db["customers"]

 

# If the collection doesn't exist, MongoDB will create it automatically

print(collection)


Basic Operations with PyMongo

1. Inserting Documents

MongoDB stores data as documents. Inserting a document into a collection is as simple as using the insert_one() or insert_many() methods.

Insert One Document:

python

CopyEdit

# Define a document to be inserted

customer = { "name": "John", "address": "Highway 37" }

 

# Insert the document into the collection

collection.insert_one(customer)

 

print("Document inserted successfully")

Insert Many Documents:

python

CopyEdit

# Define multiple documents to be inserted

customers = [

    { "name": "Alice", "address": "1234 Oak St" },

    { "name": "Bob", "address": "5678 Pine St" }

]

 

# Insert the documents into the collection

collection.insert_many(customers)

 

print("Multiple documents inserted successfully")

2. Querying Documents

To retrieve data from MongoDB, you use the find() method. It returns a cursor, which can be iterated to access documents.

Find One Document:

python

CopyEdit

# Retrieve a single document

customer = collection.find_one({"name": "John"})

print(customer)

Find All Documents:

python

CopyEdit

# Retrieve all documents from the collection

for customer in collection.find():

    print(customer)

You can also filter documents based on specific conditions.

Find with Condition:

python

CopyEdit

# Retrieve documents where name is 'Alice'

for customer in collection.find({"name": "Alice"}):

    print(customer)

3. Updating Documents

To update documents, you use the update_one() or update_many() methods.

Update One Document:

python

CopyEdit

# Update a single document (change address of John)

collection.update_one({"name": "John"}, {"$set": {"address": "New Address"}})

Update Multiple Documents:

python

CopyEdit

# Update all documents where address is 'Highway 37'

collection.update_many({"address": "Highway 37"}, {"$set": {"address": "New Highway"}})

4. Deleting Documents

You can delete documents from a collection using the delete_one() or delete_many() methods.

Delete One Document:

python

CopyEdit

# Delete a single document

collection.delete_one({"name": "John"})

Delete Multiple Documents:

python

CopyEdit

# Delete multiple documents

collection.delete_many({"address": "New Highway"})


Handling Errors and Exceptions

When working with databases, it is important to handle exceptions that may arise. Common errors include connectivity issues, invalid queries, and more.

Example of handling errors:

python

CopyEdit

try:

    # Attempt to connect to MongoDB

    client = pymongo.MongoClient("mongodb://localhost:27017/")

    db = client["mydatabase"]

    collection = db["customers"]

except pymongo.errors.ConnectionError:

    print("Could not connect to MongoDB")


Additional Operations

1.   Counting Documents:

python

CopyEdit

# Count the number of documents in a collection

count = collection.count_documents({})

print("Total documents:", count)

2.   Sorting Documents:

python

CopyEdit

# Retrieve documents and sort them by name

for customer in collection.find().sort("name"):

    print(customer)

3.   Limiting the Number of Documents Returned:

python

CopyEdit

# Retrieve only 2 documents

for customer in collection.find().limit(2):

    print(customer)


Conclusion

In this lesson, we covered the basics of using MongoDB with Python through the PyMongo driver. The steps included installing PyMongo, connecting to MongoDB, and performing common database operations such as inserting, querying, updating, and deleting documents.

Key Takeaways:

1.   PyMongo provides a simple and efficient way to interact with MongoDB from Python.

2.   MongoDB stores data as documents in collections, which are part of databases.

3.   With PyMongo, you can perform common database operations such as insert, update, delete, and query.


Practice Exercise

1.   Create a MongoDB database for a library system and insert several books into a collection.

2.   Write queries to fetch all books by a specific author.

3.   Update the details of a book and delete a book from the collection.

4o mini

You said:

Give solutions...Practice Exercise Create a MongoDB database for a library system and insert several books into a collection. Write queries to fetch all books by a specific author. Update the details of a book and delete a book from the collection.

ChatGPT said:

ChatGPT

Solutions to Practice Exercise: MongoDB Library System

In this exercise, we will create a MongoDB database for a library system, insert several books into a collection, query books by a specific author, update the details of a book, and delete a book from the collection.


Step 1: Create a MongoDB Database for the Library System

python

CopyEdit

import pymongo

 

# Connect to MongoDB

client = pymongo.MongoClient("mongodb://localhost:27017/")

 

# Create or access the library database

db = client["library"]

 

# Create or access the books collection

books_collection = db["books"]

 

print("Library database and books collection created/accessed.")


Step 2: Insert Several Books into the Collection

Here, we will insert a few sample books into the collection. Each book will have a title, author, year of publication, and genre.

python

CopyEdit

# Insert multiple book documents into the collection

books = [

    {"title": "The Catcher in the Rye", "author": "J.D. Salinger", "year": 1951, "genre": "Fiction"},

    {"title": "To Kill a Mockingbird", "author": "Harper Lee", "year": 1960, "genre": "Fiction"},

    {"title": "1984", "author": "George Orwell", "year": 1949, "genre": "Dystopian"},

    {"title": "The Great Gatsby", "author": "F. Scott Fitzgerald", "year": 1925, "genre": "Classic"},

    {"title": "Brave New World", "author": "Aldous Huxley", "year": 1932, "genre": "Dystopian"}

]

 

# Insert books into the collection

books_collection.insert_many(books)

 

print("Books inserted successfully.")


Step 3: Query Books by a Specific Author

Let's write a query to find all books by the author George Orwell.

python

CopyEdit

# Query to fetch all books by George Orwell

books_by_orwell = books_collection.find({"author": "George Orwell"})

 

# Print the results

for book in books_by_orwell:

    print(book)

Output:

css

CopyEdit

{

    "_id": ObjectId("..."),

    "title": "1984",

    "author": "George Orwell",

    "year": 1949,

    "genre": "Dystopian"

}


Step 4: Update the Details of a Book

Let’s update the details of the book "1984" (for example, changing the genre from "Dystopian" to "Science Fiction").

python

CopyEdit

# Update the genre of the book "1984"

books_collection.update_one(

    {"title": "1984"},

    {"$set": {"genre": "Science Fiction"}}

)

 

# Verify the update

updated_book = books_collection.find_one({"title": "1984"})

print("Updated Book:", updated_book)

Output:

css

CopyEdit

{

    "_id": ObjectId("..."),

    "title": "1984",

    "author": "George Orwell",

    "year": 1949,

    "genre": "Science Fiction"

}


Step 5: Delete a Book from the Collection

Let’s delete the book "Brave New World" from the collection.

python

CopyEdit

# Delete the book "Brave New World"

books_collection.delete_one({"title": "Brave New World"})

 

# Verify that the book is deleted

deleted_book = books_collection.find_one({"title": "Brave New World"})

if deleted_book is None:

    print("Book deleted successfully.")

else:

    print("Failed to delete the book.")

Output:

CopyEdit

Book deleted successfully.


Conclusion

1.   Create a MongoDB database: We created a library database and a books collection.

2.   Insert multiple books: We inserted several book documents, each with title, author, year, and genre.

3.   Query books by author: We retrieved all books written by George Orwell.

4.   Update book details: We updated the genre of the book "1984" from "Dystopian" to "Science Fiction."

5.   Delete a book: We deleted the book "Brave New World" from the collection.

These operations form the basic CRUD (Create, Read, Update, Delete) operations that can be performed on a MongoDB database using PyMongo in Python.

4o mini

You said:

WRITE 10 ASSIGNMENTS FROM ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with proper explanation in details

ChatGPT said:

ChatGPT

Assignments on MongoDB with Python (PyMongo)

Below are 10 assignments on MongoDB with Python (PyMongo), each with detailed solutions and explanations.


Assignment 1: Create a MongoDB Database for a Student Management System

Problem: Create a MongoDB database named student_management and add a collection called students. Insert at least 5 student records into the collection, each with name, age, course, and admission_date.

Solution:

1.   Create a Connection to MongoDB:

python

CopyEdit

import pymongo

 

# Connect to MongoDB

client = pymongo.MongoClient("mongodb://localhost:27017/")

 

# Create a database

db = client["student_management"]

 

# Create a collection

students_collection = db["students"]

2.   Insert Student Data:

python

CopyEdit

# Insert student records

students = [

    {"name": "John Doe", "age": 21, "course": "Computer Science", "admission_date": "2023-01-15"},

    {"name": "Alice Smith", "age": 22, "course": "Mathematics", "admission_date": "2023-02-10"},

    {"name": "Bob Brown", "age": 23, "course": "Physics", "admission_date": "2023-03-12"},

    {"name": "Charlie Johnson", "age": 20, "course": "Biology", "admission_date": "2023-04-20"},

    {"name": "David Wilson", "age": 24, "course": "Chemistry", "admission_date": "2023-05-25"}

]

 

# Insert multiple documents

students_collection.insert_many(students)

3.   Conclusion: The student_management database and students collection are created with 5 records inserted.


Assignment 2: Fetch All Students Who Are Older Than 22 Years

Problem: Write a Python script to query the students collection and fetch all students who are older than 22 years.

Solution:

1.   Querying Students:

python

CopyEdit

# Query to fetch students older than 22 years

students_older_than_22 = students_collection.find({"age": {"$gt": 22}})

 

# Display the results

for student in students_older_than_22:

    print(student)

2.   Explanation: The query uses the $gt operator to fetch all students with an age greater than 22.


Assignment 3: Update a Student's Course

Problem: Update the course of a student with the name "John Doe" to "Data Science".

Solution:

1.   Update Operation:

python

CopyEdit

# Update the course of John Doe

students_collection.update_one(

    {"name": "John Doe"},

    {"$set": {"course": "Data Science"}}

)

 

# Verify the update

updated_student = students_collection.find_one({"name": "John Doe"})

print(updated_student)

2.   Explanation: The update_one() method is used to update the first document that matches the query (name: "John Doe") by setting the new course field to "Data Science".


Assignment 4: Delete a Student Record

Problem: Delete the student record of "Bob Brown" from the students collection.

Solution:

1.   Delete Operation:

python

CopyEdit

# Delete the student Bob Brown

students_collection.delete_one({"name": "Bob Brown"})

 

# Verify deletion

deleted_student = students_collection.find_one({"name": "Bob Brown"})

if deleted_student is None:

    print("Student deleted successfully.")

else:

    print("Failed to delete the student.")

2.   Explanation: The delete_one() method deletes the document where the name is "Bob Brown". The find_one() method checks if the student still exists.


Assignment 5: Insert Books into a Library Collection

Problem: Create a library database with a collection called books. Insert at least 3 books into the collection with fields title, author, year, and genre.

Solution:

1.   Create Database and Collection:

python

CopyEdit

db = client["library"]

books_collection = db["books"]

2.   Insert Book Data:

python

CopyEdit

books = [

    {"title": "The Catcher in the Rye", "author": "J.D. Salinger", "year": 1951, "genre": "Fiction"},

    {"title": "To Kill a Mockingbird", "author": "Harper Lee", "year": 1960, "genre": "Fiction"},

    {"title": "1984", "author": "George Orwell", "year": 1949, "genre": "Dystopian"}

]

books_collection.insert_many(books)

3.   Conclusion: The library database and books collection are populated with 3 book records.


Assignment 6: Fetch All Books by a Specific Author

Problem: Write a Python script to query the books collection and fetch all books written by "George Orwell".

Solution:

1.   Query Operation:

python

CopyEdit

# Fetch books by George Orwell

books_by_orwell = books_collection.find({"author": "George Orwell"})

 

for book in books_by_orwell:

    print(book)

2.   Explanation: The find() method is used to query the collection for books where the author field is "George Orwell".


Assignment 7: Count the Number of Books in the Library

Problem: Write a Python script to count the total number of books in the books collection.

Solution:

1.   Count Operation:

python

CopyEdit

# Count the number of books in the collection

book_count = books_collection.count_documents({})

print(f"Total number of books: {book_count}")

2.   Explanation: The count_documents() method counts all documents in the collection (since no filter is provided, it counts all documents).


Assignment 8: Sort Books by Year of Publication

Problem: Write a Python script to retrieve and print all books sorted by their year of publication in ascending order.

Solution:

1.   Sorting Operation:

python

CopyEdit

# Sort books by year in ascending order

sorted_books = books_collection.find().sort("year", pymongo.ASCENDING)

 

for book in sorted_books:

    print(book)

2.   Explanation: The sort() method is used to order the books by the year field in ascending order using pymongo.ASCENDING.


Assignment 9: Find Books Published Before a Specific Year

Problem: Write a Python script to fetch all books published before the year 1950.

Solution:

1.   Query Operation:

python

CopyEdit

# Fetch books published before 1950

old_books = books_collection.find({"year": {"$lt": 1950}})

 

for book in old_books:

    print(book)

2.   Explanation: The $lt operator is used to find documents where the year is less than 1950.


Assignment 10: Update Book Genre and Delete Specific Books

Problem: Write a Python script to:

  • Update the genre of the book "1984" to "Political Fiction".
  • Delete any book that was published before 1950.

Solution:

1.   Update Genre:

python

CopyEdit

# Update the genre of "1984"

books_collection.update_one(

    {"title": "1984"},

    {"$set": {"genre": "Political Fiction"}}

)

2.   Delete Books Published Before 1950:

python

CopyEdit

# Delete books published before 1950

books_collection.delete_many({"year": {"$lt": 1950}})

3.   Conclusion: The genre of "1984" is updated, and books published before 1950 are deleted from the collection.


Summary of Key Concepts Covered:

  • Database and Collection Creation: Creating databases and collections in MongoDB.
  • CRUD Operations: Inserting, querying, updating, and deleting data using PyMongo.
  • Querying with Filters: Using operators like $gt, $lt, and $set for querying and updating.
  • Sorting and Counting: Sorting documents and counting the number of documents in a collection.
  • Deleting Documents: Removing documents based on specific criteria.

These assignments cover essential operations you need to learn in order to work with MongoDB and Python, helping you understand how to manage and manipulate data efficiently.

4o mini

You said:

WRITE 50 no of MCQs only FROM ABOVE CONCEPT with explanation

ChatGPT said:

ChatGPT

MongoDB with Python (PyMongo) - Multiple Choice Questions (MCQs)


1. What is the default port on which MongoDB runs?

  • a) 3306
  • b) 27017
  • c) 8080
  • d) 5432

Answer: b) 27017
Explanation: MongoDB runs by default on port 27017.


2. Which Python library is used to connect to MongoDB?

  • a) MySQLdb
  • b) PyMongo
  • c) psycopg2
  • d) SQLite3

Answer: b) PyMongo
Explanation: PyMongo is the official Python library used to connect to MongoDB.


3. How do you create a new MongoDB database using PyMongo?

  • a) db.create("new_db")
  • b) client.new_db()
  • c) client["new_db"]
  • d) db.create_database("new_db")

Answer: c) client["new_db"]
Explanation: A new database is created when you reference it via client["new_db"].


4. Which method is used to insert a single document in MongoDB using PyMongo?

  • a) insert_one()
  • b) add_document()
  • c) insert_document()
  • d) add_one()

Answer: a) insert_one()
Explanation: The insert_one() method is used to insert a single document in a collection.


5. Which of the following is used to create a collection in MongoDB using PyMongo?

  • a) db.create_collection("students")
  • b) client.create_collection("students")
  • c) db.new_collection("students")
  • d) client.create("students")

Answer: a) db.create_collection("students")
Explanation: To create a collection, you use db.create_collection().


6. What will the find() method return in MongoDB when used without any filters?

  • a) A single document
  • b) An empty list
  • c) A cursor object
  • d) A list of documents

Answer: c) A cursor object
Explanation: The find() method returns a cursor that iterates over the documents in a collection.


7. How do you query documents in MongoDB that match a condition in PyMongo?

  • a) find_all()
  • b) find()
  • c) query()
  • d) search()

Answer: b) find()
Explanation: The find() method is used to query documents that match a given condition.


8. Which operator is used to query for documents where a value is greater than a specified value in MongoDB?

  • a) $lt
  • b) $gt
  • c) $eq
  • d) $gte

Answer: b) $gt
Explanation: The $gt operator is used to find documents where the value of a field is greater than the specified value.


9. How do you count the number of documents in a MongoDB collection?

  • a) count_documents()
  • b) document_count()
  • c) count()
  • d) find_count()

Answer: a) count_documents()
Explanation: count_documents() is used to count the number of documents that match a given filter.


10. Which method is used to update a single document in MongoDB using PyMongo?

  • a) update_one()
  • b) modify()
  • c) update_document()
  • d) set_one()

Answer: a) update_one()
Explanation: update_one() is used to update the first document that matches the filter.


11. How do you update multiple documents in MongoDB using PyMongo?

  • a) update_all()
  • b) update_many()
  • c) bulk_update()
  • d) modify_all()

Answer: b) update_many()
Explanation: update_many() is used to update all documents that match the filter.


12. Which of the following is used to delete a document in MongoDB?

  • a) delete_one()
  • b) remove()
  • c) delete()
  • d) remove_document()

Answer: a) delete_one()
Explanation: delete_one() is used to delete a single document that matches a given filter.


13. What does the sort() method do in PyMongo?

  • a) Sorts documents by a specified field
  • b) Filters documents
  • c) Deletes documents based on a condition
  • d) Aggregates documents

Answer: a) Sorts documents by a specified field
Explanation: The sort() method sorts documents based on the specified field(s).


14. Which PyMongo operator is used to query for documents where a value is less than a specified value?

  • a) $lt
  • b) $gt
  • c) $eq
  • d) $ne

Answer: a) $lt
Explanation: The $lt operator is used to find documents where the value of a field is less than the specified value.


15. Which method is used to insert multiple documents into MongoDB using PyMongo?

  • a) insert_multiple()
  • b) insert_many()
  • c) add_many()
  • d) batch_insert()

Answer: b) insert_many()
Explanation: insert_many() is used to insert multiple documents into a collection.


16. What is the output of the find_one() method?

  • a) List of documents
  • b) A single document
  • c) Cursor object
  • d) None

Answer: b) A single document
Explanation: The find_one() method returns a single document that matches the filter.


17. Which of the following methods can be used to retrieve all books written by a specific author?

  • a) find()
  • b) search()
  • c) filter()
  • d) query()

Answer: a) find()
Explanation: The find() method is used to retrieve documents based on specific filters, such as the author name.


18. Which operator is used to query for documents that are equal to a given value in MongoDB?

  • a) $gt
  • b) $lt
  • c) $eq
  • d) $ne

Answer: c) $eq
Explanation: The $eq operator is used to query documents where a field's value is equal to the specified value.


19. What is the default behavior of the find() method in MongoDB?

  • a) Returns all documents
  • b) Returns a single document
  • c) Returns a count of documents
  • d) Returns no results

Answer: a) Returns all documents
Explanation: When no filter is provided, the find() method returns all documents from the collection.


20. What is the command used to sort the documents in ascending order by a field in PyMongo?

  • a) .sort("field", pymongo.ASCENDING)
  • b) .order_by("field")
  • c) .sort_by("field", "ascending")
  • d) .ascending("field")

Answer: a) .sort("field", pymongo.ASCENDING)
Explanation: The sort() method with pymongo.ASCENDING sorts the documents in ascending order based on the specified field.


21. Which method is used to create a MongoDB index in PyMongo?

  • a) create_index()
  • b) index_create()
  • c) add_index()
  • d) create()

Answer: a) create_index()
Explanation: The create_index() method is used to create an index on a specified field or fields in the collection.


22. What does the $set operator do in PyMongo?

  • a) Deletes a field
  • b) Sets the value of a field
  • c) Updates a field's value based on a condition
  • d) Adds a new field

Answer: b) Sets the value of a field
Explanation: The $set operator is used to set the value of a specified field in a document.


23. How do you connect to a MongoDB database in Python using PyMongo?

  • a) client.connect()
  • b) client.connect_to_db()
  • c) MongoClient()
  • d) connect.MongoClient()

Answer: c) MongoClient()
Explanation: MongoClient() is used to establish a connection to a MongoDB server in Python.


24. What is the method to remove a collection in MongoDB?

  • a) drop_collection()
  • b) remove_collection()
  • c) delete_collection()
  • d) drop()

Answer: a) drop_collection()
Explanation: The drop_collection() method is used to remove a collection from the database.


25. What is the method used to perform aggregation operations in MongoDB?

  • a) aggregate()
  • b) group()
  • c) aggregate_data()
  • d) process()

Answer: a) aggregate()
Explanation: The aggregate() method is used to perform complex operations like filtering, grouping, and sorting on MongoDB documents.


26. Which of the following is used to create an index on multiple fields in MongoDB?

  • a) create_multifield_index()
  • b) multi_index()
  • c) create_index()
  • d) add_index()

Answer: c) create_index()
Explanation: You can pass a list of fields to the create_index() method to create a multi-field index.


27. How do you connect to a remote MongoDB server in Python?

  • a) MongoClient('mongodb://remote_host')
  • b) MongoClient('remote_host')
  • c) MongoClient('mongodb://localhost')
  • d) connect('remote_host')

Answer: a) MongoClient('mongodb://remote_host')
Explanation: You can connect to a remote MongoDB server by passing the server's URL to MongoClient.


28. Which of the following is used to check if a field exists in a document in MongoDB?

  • a) $exists
  • b) $contains
  • c) $in
  • d) $not

Answer: a) $exists
Explanation: The $exists operator is used to check whether a field exists in a document.


29. Which method is used to find documents with a specified range of values in MongoDB?

  • a) find_range()
  • b) find_in_range()
  • c) find() with $gte and $lte
  • d) find_values()

Answer: c) find() with $gte and $lte
Explanation: You can use $gte (greater than or equal) and $lte (less than or equal) operators with find() to query a range of values.


30. What does ObjectId represent in MongoDB?

  • a) A unique identifier for a document
  • b) A timestamp
  • c) A collection identifier
  • d) A field identifier

Answer: a) A unique identifier for a document
Explanation: ObjectId is a unique identifier automatically generated for each document in MongoDB.


31. Which operator is used for pattern matching in MongoDB queries?

  • a) $in
  • b) $regex
  • c) $like
  • d) $pattern

Answer: b) $regex
Explanation: The $regex operator is used to perform regular expression-based pattern matching in queries.


32. How do you ensure uniqueness of a field in MongoDB?

  • a) By using the $unique index
  • b) By creating a unique index on the field
  • c) By using the unique() method
  • d) By using the $distinct operator

Answer: b) By creating a unique index on the field
Explanation: A unique index ensures that all values in the indexed field are distinct.


33. What will the following query do: db.users.delete_many({"age": {"$lt": 18}})?

  • a) Delete users with age greater than 18
  • b) Delete users with age less than 18
  • c) Delete a single user with age less than 18
  • d) Delete users with age equal to 18

Answer: b) Delete users with age less than 18
Explanation: This query deletes all users whose age is less than 18 using the $lt operator.


34. Which of the following commands is used to get the first document from a MongoDB collection?

  • a) first()
  • b) find_first()
  • c) find_one()
  • d) first_document()

Answer: c) find_one()
Explanation: The find_one() method retrieves the first document that matches the filter.


35. How do you prevent MongoDB from creating a collection automatically when data is inserted?

  • a) Set the auto_create flag to false
  • b) Set create_collection parameter to false
  • c) Use the create_collection() method manually
  • d) MongoDB will always create collections automatically

Answer: c) Use the create_collection() method manually
Explanation: MongoDB creates collections automatically when inserting data, but you can manually create a collection using create_collection() to prevent this.


36. Which operator is used to check if a value is not equal to a specified value in MongoDB?

  • a) $ne
  • b) $gt
  • c) $lt
  • d) $neq

Answer: a) $ne
Explanation: The $ne operator is used to check for values that are not equal to the specified value.


37. Which method is used to access a specific collection in MongoDB?

  • a) db.get_collection()
  • b) db["collection_name"]
  • c) db.collection()
  • d) db.select_collection()

Answer: b) db["collection_name"]
Explanation: You access a specific collection in a database by referencing it as db["collection_name"].


38. What is the result of using update_one() with an upsert option set to true?

  • a) It creates a new document if no matching document is found
  • b) It only updates an existing document
  • c) It raises an error if no matching document is found
  • d) It does nothing

Answer: a) It creates a new document if no matching document is found
Explanation: When the upsert option is set to True, MongoDB creates a new document if no matching document is found during the update operation.


39. Which of the following methods is used to insert a document if it doesn't already exist in MongoDB?

  • a) update()
  • b) insert_if_not_exists()
  • c) insert_one() with upsert=True
  • d) upsert_document()

Answer: c) insert_one() with upsert=True
Explanation: The insert_one() method with upsert=True inserts a document if it doesn't already exist based on the filter condition.


40. What will the following query do: db.students.update_one({"name": "John"}, {"$inc": {"age": 1}})?

  • a) Increase the age of the first student with the name "John" by 1
  • b) Set the age of the student named "John" to 1
  • c) Update all students with the name "John"
  • d) Add a new field age to the student named "John"

Answer: a) Increase the age of the first student with the name "John" by 1
Explanation: The $inc operator increases the value of the age field by 1.


41. Which method in PyMongo is used to execute an aggregation pipeline?

  • a) run_pipeline()
  • b) aggregate()
  • c) exec_pipeline()
  • d) process_pipeline()

Answer: b) aggregate()
Explanation: The aggregate() method is used to execute an aggregation pipeline.


42. Which method is used to retrieve the last document from a MongoDB collection in PyMongo?

  • a) find_last()
  • b) find_one() with sorting
  • c) get_last()
  • d) find() with limit(1)

Answer: b) find_one() with sorting
Explanation: To get the last document, use find_one() with sorting in descending order.


43. Which of the following methods is used to remove all documents from a MongoDB collection?

  • a) delete_all()
  • b) clear()
  • c) remove_all()
  • d) delete_many({})

Answer: d) delete_many({})
Explanation: The delete_many({}) method removes all documents in the collection when no filter is provided.


44. What is the purpose of the $set operator in MongoDB?

  • a) To replace the entire document
  • b) To add or update a field in a document
  • c) To delete a field from a document
  • d) To perform a mathematical operation on a field

Answer: b) To add or update a field in a document
Explanation: The $set operator is used to add a new field or update an existing field in a document.


45. Which of the following is a valid query operator in MongoDB?

  • a) $multiply
  • b) $div
  • c) $lt
  • d) $and

Answer: c) $lt
Explanation: $lt is a valid query operator used to find documents where a field is less than a specified value.


46. Which of the following query operators is used for checking if an array contains a value in MongoDB?

  • a) $contains
  • b) $in
  • c) $array
  • d) $elemMatch

Answer: d) $elemMatch
Explanation: The $elemMatch operator is used to match elements in an array that satisfy a specified condition.


47. Which method is used to retrieve a distinct value for a specific field in MongoDB?

  • a) distinct_values()
  • b) get_distinct()
  • c) distinct()
  • d) unique_values()

Answer: c) distinct()
Explanation: The distinct() method is used to find distinct values for a specified field in MongoDB.


48. How do you create a backup of a MongoDB database?

  • a) mongodump
  • b) backup_db()
  • c) create_backup()
  • d) dump_db()

Answer: a) mongodump
Explanation: The mongodump command is used to create a backup of a MongoDB database.


49. How do you check if a MongoDB database exists?

  • a) db.exists()
  • b) db.is_open()
  • c) db.list_collection_names()
  • d) db.get_database()

Answer: c) db.list_collection_names()
Explanation: By listing the collection names, you can verify the existence of a database.


50. What is the role of a replica set in MongoDB?

  • a) To provide high availability and data redundancy
  • b) To store data backups
  • c) To scale horizontal queries
  • d) To secure database access

Answer: a) To provide high availability and data redundancy
Explanation: A replica set in MongoDB is a group of MongoDB instances that maintain the same data set, providing high availability and redundancy.

 

Tags

Post a Comment

0Comments

Post a Comment (0)

About Me