Python/MongoDB

From Omnia
Jump to navigation Jump to search

Test

#!/usr/bin/env python3

# python -m pip install pymongo
import pymongo
import urllib.parse

# pymongo tutorial - https://www.w3schools.com/python/python_mongodb_getstarted.asp

with open('../files/mongo.username', 'r') as file:
    username = file.read().replace('\n', '')
with open('../files/mongo.password', 'r') as file:
    password = file.read().replace('\n', '')
with open('../files/mongo.server', 'r') as file:
    server = file.read().replace('\n', '')

# pymongo.errors.InvalidURI: Username and password must be escaped according to RFC 3986, use urllib.parse.quote_plus()
q_username = urllib.parse.quote_plus(username)
q_password = urllib.parse.quote_plus(password)
creds = (f"{q_username}:{q_password}")
db_url = f"mongodb://{creds}@{server}:27017/"
print(db_url)

db_client = pymongo.MongoClient(db_url)

print("List Databases:")
print(db_client.list_database_names())

# MongoDB will create the database if it does not exist, and make a connection to it.
db = db_client["test"]

# MongoDB will create the collection if it does not exist.
people = db["people"]

person = {"name": "John", "color": "blue"}
x = people.insert_one(person)
print(x.inserted_id)

person = {"name": "Mike", "color": "Green"}
x = people.insert_one(person)
print(x.inserted_id)

# Find first person in collection
first_person = people.find_one()
print("First person:")
print(first_person)

print("Find people who like blue:")
# if you want to sort:  blue_people.sort(KEY)
blue_people = people.find({"color": "blue"}).sort('name')
# print(blue_people)
for person in blue_people:
    print(person)

print("Delete blue people")
x = people.delete_many({"color": "blue"})
print(x)

# update one record
print("Updating Mike:")
x = people.update_one({"name": "Mike"}, {"$set": {"color": "red"}})
print(x)

print("Mike:")
mike = people.find_one({"name": "Mike"})
print(mike)

print("Drop collection")
people.drop()

print("Done")

keywords