Chapter 3. MongoDB
Chapter 3. MongoDB
collection.insert_many(new_recordS)
print("\nNew recordS inserted successfully.")
client.close()
DELETE DOCUMENTS
import pymongo
client = pymongo.MongoClient("localhost", 27017)
db = client["manjudb"]
collection = db["table1"]
for document in cursor:
print(document)
# Search for documents with "Budget" less than 10 and delete them
delete_result = collection.delete_many({"Budget": {"$lt": 10}})
print(f"\nDeleted {delete_result.deleted_count} records with budget less than 10.")
client.close()
*****delete_one ---will delete only the first matching document
UPDATE DOCUMENTS
import pymongo
# Connect to the MongoDB server
Logical
•$and: Returns documents where both queries match
•$or: Returns documents where either query matches
•$nor: Returns documents where both queries fail to match
•$not: Returns documents where the query does not match
Evaluation
The following operators assist in evaluating documents.
•$regex: Allows the use of regular expressions when evaluating field values
•$text: Performs a text search
•$where: Uses a JavaScript expression to match documents
AGGREGATIONS (GROUPING)
import pymongo
client = pymongo.MongoClient("localhost", 27017)
db = client["manjudb"] # Replace with your database name
collection = db["table1"] # Replace with your collection name
# Define the aggregation pipeline
pipeline = [ OUTPUT:
{ "$group": { Genre: Drama , Average Budget:
import pymongo
{
client = "mid": 191,
pymongo.MongoClient("localhost", "Budget": 95 },
27017) {"mid": 171,
db = client["manjudb"] "Genre": "Action" }]
db.create_collection("movie")
collection.insert_many(new_recordS)
collection = db["movie"]
new_recordS = [{ client.close()
"mid": 181,
"Budget": 95 },
LIMIT
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017")
# Select the database and collection
db = client["manjudb"]
collection = db["sample"]
# Perform the find operation with the limit
results = collection.find().limit(2)
for document in results:
print(document)
INDEXING
import pymongo
client = pymongo.MongoClient("mongodb://localhost:27017")
db = client["manjudb"]
collection = db["table1"]
# Create an index on a specific field (e.g., "field_name")
index_key = [("Budget", pymongo.ASCENDING)] # You can use DESCENDING for descending order
collection.create_index(index_key)
# Example query using the index
query = {"Budget": 10}
results = collection.find(query).limit(5)
for document in results:
print(document)