Table
1. How to install MongoDB by pip?
- Install PyMongo
1 |
pip3 install pymongo |
- We will use the mongodb srv url, then we need install dnspython.
1 |
pip3 install dnspython |
2. How to Connect Mongodb with python?
1 2 3 4 5 6 7 8 |
import pymongo import random db_client = pymongo.MongoClient( "mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/" ) databse = mb_client["<database>"] collection = databse["<collection>"] |
3. Read data
- find one
1 |
cursor = collection.find_one({'<column_name>': '<what_you_want>'}) |
2. find all
1 |
cursor = collection.find({'<column_name>': '<what_you_want>'}) |
4. Create data
- insert one
1 2 3 4 5 6 7 |
item = { "item_name" : "Max", "quantity" : 2, "ingredients" : "all-purpose flour", "expiry_date" : expiry } collection.insert_one(item) |
2. insert many
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
item_1 = { "item_name" : "Maxlist", "max_discount" : "10%", "batch_number" : "RR450020FRG", "price" : 340, "category" : "python" } item_2 = { "item_name" : "Maxlist.xyz", "category" : "python", "quantity" : 12, "price" : 36, "item_description" : "mongodb" } collection.insert_many([item_1,item_2]) |
5. Update data
update_one
1 2 3 4 5 6 7 8 9 |
collection.update_one( {"discordId": str(discordId)}, {"$set": {"verifyString": "pass"}}, ) collection.update_one( {"inviteCode." + text: True}, {"$set": {"inviteCode.$." + text: False}}, ) |