Skip to content

PYMONGO

PYMONGO:

Topics

  • READ
  • CREATE
  • UPDATE
  • DELETE

READ

import pymongo

# client
clientURI = "mongodb+srv://..."
client = pymongo.MongoClient(clientURI)

# dbs
db_name = "YB100DB"
db_names = client.list_database_names()
db = client[db_name]
print ('db_names: ', db_names)
print ('db ', db)

# collection 
collection_name = "_MAIN"
collection_names = db.list_collection_names()
collection = db[collection_name]
print ('collection_names: ', collection_names)
print ('collection ', collection)

# document
total_docs = collection.count_documents({})
documents = collection.find().sort("_id", -1)
document = documents[0]
document2 = collection.find_one()

print ('documents: ', documents)
print ('documents ', document)

CREATE

inserted_id = new_collection.insert_one(mainObject)
        print("inserted_id ", inserted_id)

UPDATE

print ('UPDATE ', UPDATE)
object_ID = 'list-object'
myquery = {"_id": object_ID}
newvalues = {"$set": mainObject}
inserted_id = new_collection.update_one(myquery, newvalues)

DELETE

print ('DELETE ', DELETE)
document_id = 'test'
deleted = collection.delete_one({"_id": document_id})