DEV Community

Cover image for MONGOdb šŸƒ in python project!
Bogusdeck
Bogusdeck

Posted on

MONGOdb šŸƒ in python project!

Introduction

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.

Creating a Database

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

Sort the Result

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

Insertion

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

Deletion

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

Updation

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

Searching a query

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

Top comments (0)