[Python] Quick Start & Cheatsheet for MongoDB

Qurick start with mongodb

1. How to install MongoDB by pip?

  1. Install PyMongo
pip3 install pymongo
  1. We will use the mongodb srv url, then we need install dnspython.
pip3 install dnspython

2. How to Connect Mongodb with python?

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

  1. find one
cursor = collection.find_one({'<column_name>': '<what_you_want>'})

2. find all

cursor = collection.find({'<column_name>': '<what_you_want>'})

4. Create data

  1. insert one
item = {
"item_name" : "Max",
"quantity" : 2,
"ingredients" : "all-purpose flour",
"expiry_date" : expiry
}
collection.insert_one(item)

2. insert many

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

collection.update_one(
    {"discordId": str(discordId)},
    {"$set": {"verifyString": "pass"}},
)

collection.update_one(
    {"inviteCode." + text: True},
    {"$set": {"inviteCode.$." + text: False}},
)

Reff

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。