1. 程式人生 > >資料儲存之使用MongoDB資料庫儲存資料

資料儲存之使用MongoDB資料庫儲存資料

安裝MongoDB環境:

1.官網下載:https://www.mongodb.com/download-center#community
2.MongoDB視覺化工具compass下載https://www.mongodb.com/download-center#compass

筆記

import pymongo


# 獲取連線Mongodb的物件
client = pymongo.MongoClient('127.0.0.1',port=27017)

# 獲取資料庫(如果沒有當前資料庫也沒關係)
db = client.zhihu

# 獲取資料庫的集合(MySQL中的表類似)
collection = db.qa

# 寫入資料
# collection.insert({'name':'123'})

# 插入資料
# collection.insert_many([
#     {
#         "username":"bbb",
#         "age":18
#     },{
#         "username":"ccc",
#         "age":19
#     }
# ])

# 查詢資料(返回遊標)
# cursor = collection.find()
# for x in cursor:
#     print(x)

# 獲取集合中一條資料(可以指定條件)
# result = collection.find_one({'name':'123'})
# print(result)

# 更新一條資料
# collection.update_one({'username':'ccc'},{'$set':{'username':'aaa'}})

# 更新多條資料(第一個引數是更新那條資料,第二個引數是更新後的資料)
# collection.update_many({'username':'aaa'},{'$set':{'username':'123'}})

# 刪除一條資料
# collection.delete_one({'name':'123'})

# 刪除多條資料(第一個引數是刪除那條資料)
# collection.delete_many({'username':'123'})