pymongo的基本操作:增删改查
生活随笔
收集整理的這篇文章主要介紹了
pymongo的基本操作:增删改查
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
導(dǎo)入pymongo并選擇要操作的集合 數(shù)據(jù)庫和集合乜有會自動創(chuàng)建
from pymongo import MongoClient
client = MongoClient(host,port)
collection = client[db名][集合名]
添加一條數(shù)據(jù)
ret = collection.insert_one({"name":"test10010","age":33})
print(ret)
添加多條數(shù)據(jù)
item_list = [{"name":"test1000{}".format(i)} for i in range(10)]
#insert_many接收一個列表,列表中為所有需要插入的字典
t = collection.insert_many(item_list)
查找一條數(shù)據(jù)
#find_one查找并且返回一個結(jié)果,接收一個字典形式的條件
t = collection.find_one({"name":"test10005"})
print(t)
查找全部數(shù)據(jù)
結(jié)果是一個Cursor游標(biāo)對象,是一個可迭代對象,可以類似讀文件的指針,但是只能夠進(jìn)行一次讀取
#find返回所有滿足條件的結(jié)果,如果條件為空,則返回數(shù)據(jù)庫的所有
t = collection.find({"name":"test10005"})
#結(jié)果是一個Cursor游標(biāo)對象,是一個可迭代對象,可以類似讀文件的指針,
for i in t:
print(i)
for i in t: #此時t中沒有內(nèi)容
print(i)
更新一條數(shù)據(jù) 注意使用$set命令
#update_one更新一條數(shù)據(jù)
collection.update_one({"name":"test10005"},{"$set":{"name":"new_test10005"}})
更行全部數(shù)據(jù)
# update_one更新全部數(shù)據(jù)
collection.update_many({"name":"test10005"},{"$set":{"name":"new_test10005"}})
刪除一條數(shù)據(jù)
#delete_one刪除一條數(shù)據(jù)
collection.delete_one({"name":"test10010"})
刪除全部數(shù)據(jù)
#delete_may刪除所有滿足條件的數(shù)據(jù)
collection.delete_many({"name":"test10010"})
總結(jié)
以上是生活随笔為你收集整理的pymongo的基本操作:增删改查的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大脚趾痛(大脚趾痛要区分原因)
- 下一篇: 种植牙好吗