MONGOdb 🍃 in python project!

PyMongo is a Python driver for MongoDB, a popular NoSQL database. MongoDB is a document-oriented database that stores data in flexible, JSON-like documents, and PyMongo allows Python applications to interact with MongoDB.

With PyMongo, you can perform various database operations, such as inserting, updating, deleting, and querying documents. It provides a convenient and Pythonic way to work with MongoDB, allowing you to use Python data structures and idioms directly.

Install PyMongo

pip install pymongo
Enter fullscreen mode Exit fullscreen mode

Connect to MongoDB

import pymongo # Connect to MongoDB server (default: localhost, port: 27017)
client = pymongo.MongoClient("mongodb://localhost:27017/")
Enter fullscreen mode Exit fullscreen mode

Create or Select a Database

# Create or select a database
mydatabase = client["mydatabase"]
Enter fullscreen mode Exit fullscreen mode

Create or Select a Collection

# Create or select a collection
mycollection = mydatabase["mycollection"]
Enter fullscreen mode Exit fullscreen mode

Use the sort() method to sort the result in ascending or descending order.

The sort() method takes one parameter for “field name” and one parameter for “direction” (ascending is the default direction)

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] mydoc = mycol.find().sort("name") #for descending .sort("name",-1)

for x in mydoc: print(x)
Enter fullscreen mode Exit fullscreen mode

Insert Documents

# Insert a single document
document = {"name": "John", "age": 30, "city": "New York"}
result = mycollection.insert_one(document)
print(f"Inserted document ID: {result.inserted_id}")
Enter fullscreen mode Exit fullscreen mode

Insert Multiple Documents

# Insert multiple documents
documents = [ {"name": "Alice", "age": 25, "city": "San Francisco"}, {"name": "Bob", "age": 35, "city": "Los Angeles"}
]
result = mycollection.insert_many(documents)
print(f"Inserted {len(result.inserted_ids)} documents")
Enter fullscreen mode Exit fullscreen mode

Delete one document

# Delete a document
mycollection.delete_one({"name": "John"})
Enter fullscreen mode Exit fullscreen mode

Delete multiple documents

# Delete multiple documents
mycollection.delete_many({"city": "Brooklyn"})
Enter fullscreen mode Exit fullscreen mode

Delete all documents in a collections

x = mycol.delete_many({}) print(x.deleted_count, " documents deleted.")
Enter fullscreen mode Exit fullscreen mode

Delete a collection

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] mycol.drop()
Enter fullscreen mode Exit fullscreen mode

Update a single documents

# Update a document
mycollection.update_one({"name": "John"}, {"$set": {"age": 31}})
Enter fullscreen mode Exit fullscreen mode

alternate method

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] myquery = { "address": "Valley 345" }
newvalues = { "$set": { "address": "Canyon 123" } } mycol.update_one(myquery, newvalues) #print "customers" after the update:
for x in mycol.find(): print(x)
Enter fullscreen mode Exit fullscreen mode

Update multiple documents

# Update multiple documents
mycollection.update_many({"city": "New York"}, {"$set": {"city": "Brooklyn"}})
Enter fullscreen mode Exit fullscreen mode

To select data from a collection in MongoDB, we can use the find_one() method.

The find_one() method returns the first occurrence in the selection.

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] x = mycol.find_one() print(x)
Enter fullscreen mode Exit fullscreen mode

To select data from a table in MongoDB, we can also use the find() method.

The find() method returns all occurrences in the selection.

The first parameter of the find() method is a query object. In this example we use an empty query object, which selects all documents in the collection.

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] for x in mycol.find(): print(x)
Enter fullscreen mode Exit fullscreen mode

using second parameter in find()

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] for x in mycol.find({},{ "_id": 0, "name": 1, "address": 1 }): print(x)
Enter fullscreen mode Exit fullscreen mode

Filter the result

When finding documents in a collection, you can filter the result by using a query object.

The first argument of the find() method is a query object, and is used to limit the search.

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] myquery = { "address": "Park Lane 38" } mydoc = mycol.find(myquery) for x in mydoc: print(x)
Enter fullscreen mode Exit fullscreen mode

Advance query

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] myquery = { "address": { "$gt": "S" } } mydoc = mycol.find(myquery) for x in mydoc: print(x)
Enter fullscreen mode Exit fullscreen mode

Limit the query result

import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"] myresult = mycol.find().limit(5) #print the result:
for x in myresult: print(x)
Enter fullscreen mode Exit fullscreen mode

Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top
Interpersonal relationships life skills.