pip install pymongo 基本使用:insert() remove() update() find() 官方推薦:insert_one() delete_one() update_one() find_one() ...
pip install pymongo
import pymongo
# 建立連接
client = pymongo.MongoClient()
# 指定資料庫 (不存在則會新建)
db = client['py_mongo']
# 刪除資料庫
# client.drop_database('py_mongo_temp')
# 創建集合
# db.create_collection('col_temp')
# 刪除集合
# print(db.drop_collection('col_temp'))
# 指定集合 (不存在則會新建)
collection = db['mongo_col']
# collection = pymongo.MongoClient()['py_mongo']['mongo_col']
基本使用:insert() 、 remove() 、 update() 、 find()
# 增 insert()
# 如果不指定_id參數,MongoDB會為文檔分配一個唯一的ObjectId
# 增加一條
# collection.insert({'_id':1,'name':'JiYu','num':0})
# 增加多條
# collection.insert( [
# {'name':'jiyu','num':12},
# {'name':'jiyu','num':34},
# {'name':'nianhua','num':12},
# {'name':'nianhua','num':34},
# ] )
# 刪 remove()
# 刪除集合中滿足條件的所有文檔
# collection.remove({'name':'jiyu'})
# 只刪除集合中滿足條件的第一條文檔
# collection.remove({'name':'nianhua'},multi=False)
# 刪除所有
# collection.remove()
# 改 update()
# 修改一條數據 只有name,沒有num了,整條數據變成<update>里的內容
# collection.update({'name':'jiyu'},{'name':'nianhua'})
# 指定屬性修改 $set
# collection.update({'name':'jiyu'},{'$set':{'name':'nianhua'}})
# 修改集合中所有滿足條件的文檔:multi: true
# collection.update({'name':'nianhua'},{'$set':{'name':'NianHua'}},multi=True)
# 查 find()
# 查詢所有
# for i in collection.find():
# print(i)
# 根據條件查詢
# for i in collection.find({'name': 'NianHua'}):
# print(i)
# and 和 or 條件
# condition = {'$or': [{'num': 12}, {'name': 'NianHua'}]}
# for i in collection.find(condition):
# print(i)
# 操作符
# for i in collection.find({'num': {'$gt': 20}}):
# print(i)
官方推薦:insert_one() 、 delete_one() 、 update_one() 、 find_one()
# 增 insert_one() insert_many()
# 添加一條
# collection.insert_one({'name':'ming','num':101})
# 添加多條
# collection.insert_many( [
# {'name':'hong','num':111},
# {'name':'fei','num':111}
# ] )
# 刪 delete_one() delete_many()
# 刪除一條
# collection.delete_one({'num': 111})
# 刪除多條
# collection.delete_many({'name':'NianHua'})
# 改 update_one() update_many()
# 需要用$進行操作,加上$set,否則會報錯:update only works with $ operators
# 修改一條
# collection.update_one({'name':'jiyu'},{'$set':{'num':99}})
# 修改多條
# collection.update_many({'name':'jiyu'},{'$set':{'num':99}})
# 查 find_one() find()
# 查一條
# print(collection.find_one({'num':111}))
# 查找所有 find() 只是一個對象 用for 遍歷出來
for i in collection.find():
print(i)