MangoDB
安裝
安裝 MongoDB
安裝 pymongo
安裝 MongoDB for VS Code
資料庫結構
| 資料庫結構 (大 → 小) | |||
| MySQL | database | table | row of data |
| MongoDB | database | collection | document |
操作
連接資料庫
pymongo
from pymongo import MongoClient
db_name = '...'
collection_name = '...'
client = MongoClient('mongodb://localhost:27017/')
database = client[db_name]
collection = database[collection_name]
確認 database / collection 是否已存在
if "..." in client.list_database_names():
...if "..." in client.list_collection_names():
...
操作方法
| MongoDB methods | PyMongo methods1PyMongo Doc. | |
| 插入 | insertOne() | insert_one() |
| insertMany() | insert_many() | |
| 搜尋 |
find() | find() |
| findOne() | find_one() | |
| 更新 | updateOne() | update_one() |
| updateMany() | update_many() | |
| 搜尋並更新 (避免並行執行時出錯) |
findOneAndUpdate() | find_one_and_update() |
| 刪除 | deleteOne() | delete_one() |
| deleteMany() | delete_many() |
document 中的「_id」
每一個 document 都一定有一個_id的 key
如果沒有預先指定的話,系統會隨機賦值
指定 _id
document["_id"] = "..."
collection.insert_one(document)
更新
collection.update_one(filter, update)⇒ 更新符合條件的第一筆資料collection.update_many(filter, update)⇒ 更新符合條件的所有資料
filter
{key1: value1, key2: value2, …}
update2MongoDB Manual: Update Oprator
Syntax
{
"$<operator_1>": { <field_1_1>: <value_1_1>, ... },
"$<operator_2>": { <field_2_1>: <value_2_1>, ... },
...
}
Operator: Fields
Operator: Array
Operator: Modifiers
Operator: Bitwise
搜尋
列出 document 所有的 key
collection.find_one({_id-value}) ⇒ <class 'dict'>
如果名為 _id-value 的 document 已存在: insert_…() ⇒ update_...()
if collection.find_one_and_update({"_id": {_id-value}}, ...) is None:
collection.insert_one(...)
Last Updated on 2025/01/12 by A1go