MongoDB数据库(8.Python中使用mongodb数据库以及pymongo模块用法)
生活随笔
收集整理的這篇文章主要介紹了
MongoDB数据库(8.Python中使用mongodb数据库以及pymongo模块用法)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
在Python中使用MongoDB數(shù)據(jù)庫,首先要下載pymongo模塊
直接在命令行? ?pip install pymongo? ?就可以了
Python中使用pymongo模塊對MongoDB數(shù)據(jù)庫進(jìn)行操作,增刪改查。。。。。。
?導(dǎo)入模塊
from pymongo import MongoClient建立數(shù)據(jù)庫連接
# 建立和MongoDB數(shù)據(jù)庫的連接 client = MongoClient(host="127.0.0.1", port=27017) '''使用方括號的方式選擇數(shù)據(jù)庫和集合如果數(shù)據(jù)庫里面沒有相應(yīng)的數(shù)據(jù)庫和集合,就會創(chuàng)建 ''' collecions = client["Test04"]["set_01"]pymongo插入數(shù)據(jù)
'''1.插入一條數(shù)據(jù) insert()''' collecions.insert({"name": "Python", "age": 10}) # 1.1 給插入語句賦個值,打印出這條數(shù)據(jù)的文檔id res = collecions.insert({"name": "Java", "age": 10}) print(res) # 輸出 5c8e4cc0014b71ac088b4c7d 即id '''2.插入多條數(shù)據(jù) insert_many()''' # 把想要插入的多條數(shù)據(jù)都放在一個列表中 data_list = [{"name": "test{}".format(i)} for i in range(10)] collecions.insert_many(data_list)pymongo查詢數(shù)據(jù)
'''1.查詢一個記錄 find_one()''' t1 = collecions.find_one({"name": "Python"}) # 打印的話直接打印出查找到的這條數(shù)據(jù) print(t1) '''2.查詢所有的數(shù)據(jù), find()''' t2 = collecions.find() # 直接打印會打印 一個Cursor(游標(biāo)) 對象 即 <pymongo.cursor.Cursor object at 0x000001A2AFCD1860> print(t2) # 2.1利用for循環(huán)來遍歷這個Cursor for i in t2:print(i) '''只能循環(huán)一次,因為是一個游標(biāo)的對象,所以再次循環(huán)時,這個游標(biāo)已經(jīng)到數(shù)據(jù)的最后了然后就不會打印 ''' # 2.2 可以直接把這個Cursor的游標(biāo)對象直接轉(zhuǎn)化為一個列表 # (前提是這個游標(biāo)沒有被循環(huán),即游標(biāo)的位置還在最開頭) print(list(t2))pymongo更新數(shù)據(jù)
'''1.更新一條數(shù)據(jù) update_one''' # 更新name為java的第一條數(shù)據(jù),更改為JavaEE collecions.update_one({"name": "Java"}, {"$set": {"name": "JavaEE"}}) '''2.更新全部數(shù)據(jù) update_many''' # 更新name為python_web的對應(yīng)的age屬性,所有符合條件的數(shù)據(jù)更新為20 collecions.update_many({"name": "python_web"}, {"$set": {"age": 20}})pymongo刪除數(shù)據(jù)
'''1.刪除一條數(shù)據(jù) ''' # 刪除name為JavaEE的一條數(shù)據(jù) collecions.delete_one({"name": "JavaEE"}) '''2.刪除所有滿足條件的數(shù)據(jù)''' # 刪除name為python_web的滿足條件的所有數(shù)據(jù) collecions.delete_many({"name": "python_web"})?
練習(xí)
from pymongo import MongoClientclient = MongoClient(host="127.0.0.1", port=27017) """1. 使用Python向集合中t3中插入1000條文檔,文檔的屬性包括_id、name、· _id的值為0、1、2、3···999· name的值為'py0'、'py1'..... """ collections = client["test4"]["t3"]data_list = [{"_id": i, "name": "py{}".format(i)} for i in range(1000)] collections.insert_many(data_list) print("數(shù)據(jù)操作成功")"""查詢顯示出_id為100的整數(shù)倍的文檔,如100、200、300.....,并將name輸出 """ ret = collections.find() data_list = list(ret) data_list = [i["name"] for i in data_list if i["_id"] % 100 == 0 and i["_id"] != 0] print(data_list)?
總結(jié)
以上是生活随笔為你收集整理的MongoDB数据库(8.Python中使用mongodb数据库以及pymongo模块用法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MongoDB(7.mongodb中创建
- 下一篇: Python中的GIL(全局解释器锁)