Updated on 2023-09-27 GMT+08:00

Accessing a Database

Assume that the client application has connected to the database and a MongoClient client is initialized.

Accessing DataBase

If an initialized MongoClient instance exists, run the following command to access a database:

db=client.test_database

Alternatively, use the following method:

db=client["test_database"]

Assessing a Collection

collection=db.test_collection

Alternatively, use the following method:

collection=db["test_collection"]

Creating a Collection

You can use the createCollection() method to create a collection and specify the attributes of the collection.

collection = db.create_collection("test")

Inserting Data

student = {
    'id': '20170101',
    'name': 'Jordan',
    'age': 20,
    'gender': 'male'
}
result = collection.insert(student);

Deleting Data

result = collection.delete_one({'name': 'Kevin'})

Deleting a Table

db.drop_collection("test")

Reading Data

result = collection.find_one({'name': 'Mike'})

Query with Filter Criteria

result = collection.find_one({"author":"Mike"}

Running Commands

Run buildInfo and collStats.

db.command("collstats","test")
db.command("buildinfo")

Counting

count = collection.find().count()db.command("buildinfo")

Sorting

results = collection.find().sort('name', pymongo.ASCENDING)
print([result['name'] for result in results])

Creating an Index

 result=db.profiles.create_index([('user_id',pymongo.ASCENDING)],... unique=True)