mongodb创建用户名和密码_Python中使用MongoDB详解
介紹
MongoDB是一種面向文檔型的非關(guān)系型數(shù)據(jù)庫(kù)(NoSQL),由C++編寫。非關(guān)系數(shù)據(jù)庫(kù)中是以鍵值對(duì)存儲(chǔ),結(jié)構(gòu)不固定,易存儲(chǔ),減少時(shí)間和空間的開銷。文檔型數(shù)據(jù)庫(kù)通常是以JSON或XML格式存儲(chǔ)數(shù)據(jù),而Mongodb使用的數(shù)據(jù)結(jié)構(gòu)是BSON(二進(jìn)制JSON),和JSON相比,BSON提高了存儲(chǔ)和掃描效率,但空間占用會(huì)更多一些。
在python中操作MongoDB,我們使用PyMongo,下面著重介紹。
PyMongo的使用
前提:安裝了MongoDB服務(wù)器,若沒有,點(diǎn)擊這里安裝
1.安裝
pip3 install pymongo2.連接
- 第1種方式:
- 第2種方式:
判斷是否連接成功:
print(mongo_client.server_info()) #判斷是否連接成功3.獲取Database 和 Collection
若沒有Database 和Collection,則會(huì)自動(dòng)創(chuàng)建
第一種方式:
mongo_db = mongo_client['你的database'] mongo_collection = mongo_db['你的collection']第二種方式:
mongo_db = mongo_client.你的database mongo_collection = mongo_db.你的collectionCURD操作
4.插入單條數(shù)據(jù) insert_one()
insert_one() 詳細(xì)說明參考
import datetime info = {'name' : 'Zarten','text' : 'Inserting a Document','tags' : ['a', 'b', 'c'],'date' : datetime.datetime.now() } mongo_collection.insert_one(info)5.插入多條數(shù)據(jù) insert_many()
insert_many() 詳細(xì)說明參考
import datetime info_1 = {'name' : 'Zarten_1','text' : 'Inserting a Document','tags' : ['a', 'b', 'c'],'date' : datetime.datetime.now() }info_2 = {'name' : 'Zarten_2','text' : 'Inserting a Document','tags' : [1, 2, 3],'date' : datetime.datetime.now() }insert_list = [info_1, info_2] mongo_collection.insert_many(insert_list)6.插入字符串類型的時(shí)間
由上圖可以看到插入字符串時(shí)間時(shí),mongodb自動(dòng)轉(zhuǎn)成了 ISOdate類型,若需要時(shí)間在mongdb也是字符串類型,只需這樣操作即可
datetime.datetime.now().isoformat()7.刪除一條數(shù)據(jù) delete_one()
delete_one() 詳細(xì)說明參考
刪除一條數(shù)據(jù)。若刪除條件相同匹配到多條數(shù)據(jù),默認(rèn)刪除第一條
刪除前的數(shù)據(jù)如下:
mongo_collection.delete_one({'text' : 'a'})刪除后的數(shù)據(jù)如下:
8.刪除多條數(shù)據(jù) delete_many()
delete_many() 詳細(xì)說明參考
刪除滿足條件的所有數(shù)據(jù)
刪除前的數(shù)據(jù)如下:
mongo_collection.delete_many({'text' : 'a'})刪除后的數(shù)據(jù)如下:
9.更新單條數(shù)據(jù) update_one()
update_one() 詳細(xì)說明參考
只會(huì)更新滿足條件的第一條數(shù)據(jù)
update_one(filter,update,upsert=False,bypass_document_validation=False,collation=None,array_filters=None,session=None)
- 第一個(gè)參數(shù) filter:更新的條件
- 第二個(gè)參數(shù) update : 更新的內(nèi)容,必須用$操作符
- 第三個(gè)參數(shù) upsert : 默認(rèn)False。若為True,更新條件沒找到,則插入更新的內(nèi)容
更新前的數(shù)據(jù)如下:
info = {'name': '桃子 ','text': 'peach','tags': [1, 2, 3],'date': datetime.datetime.now()} update_condition = {'name' : 'Zarten_2'} #更新的條件,也可以為多個(gè)條件 #更新條件多個(gè)時(shí),需要同時(shí)滿足時(shí)才會(huì)更新 # update_condition = {'name' : 'Pear', # 'text' : '梨子'}mongo_collection.update_one(update_condition, {'$set' : info})更新后的數(shù)據(jù):
10.更新多條數(shù)據(jù) update_many()
update_many() 詳細(xì)說明參考
更新滿足條件的所有數(shù)據(jù)
更新前的數(shù)據(jù)如下:
info = {'name': 'Zarten','text': 'a','tags': [1, 2, 3],'date': datetime.datetime.now()} update_condition = {'text' : 'a'} #更新的條件 #更新條件多個(gè)時(shí),需要同時(shí)滿足時(shí)才會(huì)更新 # update_condition = {'name' : 'Pear', # 'text' : '梨子'}mongo_collection.update_many(update_condition, {'$set' : info})11.更新時(shí),若無滿足條件,則插入數(shù)據(jù)
update_one() 詳細(xì)說明參考
通過設(shè)置upsert為True即可
更新前的數(shù)據(jù)如下:
info = {'name': 'Banana','text': '香蕉','tags': [1, 2, 3],'date': datetime.datetime.now() } update_condition = {'text' : 'a'} #更新的條件 #更新條件多個(gè)時(shí),需要同時(shí)滿足時(shí)才會(huì)更新 # update_condition = {'name' : 'Pear', # 'text' : '梨子'}mongo_collection.update_many(update_condition, {'$set' : info}, upsert= True)更新后的數(shù)據(jù)如下:
12.查詢一條數(shù)據(jù) find_one()
find_one() 詳細(xì)說明
匹配第一條滿足的條件的結(jié)果,這條結(jié)果以dict字典形式返回,若沒有查詢到,則返回None
find_condition = {'name' : 'Banana','text' : 'peach' } find_result = mongo_collection.find_one(find_condition)可以通過projection參數(shù)來指定需要查詢的字段,包括是否顯示 _id ,更多具體用法參考 find()
find_condition = {'name' : 'Zarten_3', } select_item = mongo_collection.find_one(find_condition, projection= {'_id':False, 'name':True, 'num':True}) print(select_item)13.查詢范圍
查詢范圍具體參考這里
范圍查詢通常用$ 例如:$gte 大于等于 $lt 小于;具體的$符號(hào)在文章末尾查看
例如:查詢一段時(shí)間內(nèi)的數(shù)據(jù)
import datetime find_condition = {'date' : {'$gte':datetime.datetime(2018,12,1), '$lt':datetime.datetime(2018,12,3)} } select_item = mongo_collection.find_one(find_condition) print(select_item)14.查詢多條數(shù)據(jù) find()
find() 詳細(xì)說明
返回滿足條件的所有結(jié)果,返回類型為 Cursor ,通過迭代獲取每個(gè)查詢結(jié)果,每個(gè)結(jié)果類型為dict字典
find_condition = {'name' : 'Banana','text' : '香蕉' } find_result_cursor = mongo_collection.find(find_condition) for find_result in find_result_cursor:print(find_result)15.通過 _id 來查詢
查詢條件中_id 類型是ObjectId類型,也就是插入時(shí)返回的對(duì)象。
若 _id 提供的是str類型的,我們需要轉(zhuǎn)成ObjectId類型
from bson.objectid import ObjectId query_id_str = '5c00f60b20b531196c02d657' find_condition = {'_id' : ObjectId(query_id_str), } find_result = mongo_collection.find_one(find_condition) print(find_result)16.查詢一條數(shù)據(jù)同時(shí)刪除 find_one_and_delete()
find_one_and_delete(filter,projection=None,sort=None,session=None,**kwargs) 詳細(xì)說明
- filter:查詢條件
- projection:選擇返回和不返回的字段
- sort:list類型,當(dāng)查詢匹配到多條數(shù)據(jù)時(shí),根據(jù)某個(gè)條件排序,函數(shù)返回時(shí)返回第一條數(shù)據(jù)
只能返回一條數(shù)據(jù)
此函數(shù)的特別之處在于,它會(huì)返回被刪除的信息,以字典dict形式返回
刪除前的數(shù)據(jù):
17.查詢并刪除,匹配單條數(shù)據(jù)
find_condition = {'name' : 'Banana', } deleted_item = mongo_collection.find_one_and_delete(find_condition) print(deleted_item)18.查詢并刪除,匹配多條數(shù)據(jù),有選擇的返回某條數(shù)據(jù)
通過sort參數(shù)
find_condition = {'name' : 'Zarten_2', } deleted_item = mongo_collection.find_one_and_delete(find_condition, sort= [('num', pymongo.DESCENDING)]) print(deleted_item)刪除后的數(shù)據(jù):
19.計(jì)數(shù)
count_documents() 詳細(xì)說明
注意:此函數(shù)在3.7版本添加,以下的版本無法使用,本人版本為3.6.3 固無法使用
find_condition = {'name' : 'Zarten_1' } select_count = mongo_collection.count_documents(find_condition) print(select_count)20.創(chuàng)建索引 create_index()
create_index() 詳細(xì)說明
插入數(shù)據(jù)時(shí),已經(jīng)有一個(gè)_id索引了,我們還可以自定義創(chuàng)建索引
參數(shù) unique設(shè)置為True時(shí),創(chuàng)建一個(gè)唯一索引,索引字段插入相同值時(shí)會(huì)自動(dòng)報(bào)錯(cuò)。默認(rèn)為False,為False時(shí)可以插入相同值
mongo_collection.create_index('name', unique= True)21.獲取索引信息
list_indexes() 和 index_information() 詳細(xì)說明參考這里
# list_indexs = mongo_collection.list_indexes() # for index in list_indexs: # print(index)index_info = mongo_collection.index_information() print(index_info)由上圖可以看到:
索引的名稱自動(dòng)作了處理,變成了別名 name_1
22.刪除索引 drop_index() 和 drop_indexes()
詳細(xì)參考這里
需要使用索引的別名,沒有則拋出錯(cuò)誤
del_index = mongo_collection.drop_index('name_1') print(del_index)23.刪除集合 drop()
mongo_collection.drop()24.符號(hào)$參考表
Pymongo常用操作
- 根據(jù)_id查詢數(shù)據(jù)插入時(shí)間排序
- 根據(jù)_id查詢某個(gè)日期插入的數(shù)據(jù)
比如查詢今天插入的所有數(shù)據(jù)
import datetime from bson.objectid import ObjectIdtoday_zero = datetime.datetime.strptime(datetime.datetime.now().strftime("%Y-%m-%d"), "%Y-%m-%d") dummy_id = ObjectId.from_datetime(today_zero) results = col.find({"_id": {"$gte": dummy_id}}).limit(10) for result in results:print(result)比如查詢15天前的那天日期的所有插入數(shù)據(jù)
import datetime from bson.objectid import ObjectIdstart_day_time = datetime.datetime.today() - datetime.timedelta(15) end_day_time = datetime.datetime.today() - datetime.timedelta(14)start_day_zero = datetime.datetime.strptime(start_day_time.strftime("%Y-%m-%d"), "%Y-%m-%d") end_day_zero = datetime.datetime.strptime(end_day_time.strftime("%Y-%m-%d"), "%Y-%m-%d")start_dummy_id = ObjectId.from_datetime(start_day_zero) end_dummy_id = ObjectId.from_datetime(end_day_zero)results_count = col.find({"_id": {"$gte": start_dummy_id,"$lte":end_dummy_id}}).count() print(results_count)比如昨天插入數(shù)據(jù)
start_day_time = datetime.datetime.today() - datetime.timedelta(1) end_day_time = datetime.datetime.today() - datetime.timedelta(0)start_day_zero = datetime.datetime.strptime(start_day_time.strftime("%Y-%m-%d"), "%Y-%m-%d") end_day_zero = datetime.datetime.strptime(end_day_time.strftime("%Y-%m-%d"), "%Y-%m-%d")start_dummy_id = ObjectId.from_datetime(start_day_zero) end_dummy_id = ObjectId.from_datetime(end_day_zero)results_count = col.find({"_id": {"$gte": start_dummy_id,"$lte":end_dummy_id}}).count()print(results_count)總結(jié)
以上是生活随笔為你收集整理的mongodb创建用户名和密码_Python中使用MongoDB详解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: myeclipse写简单bbs代码_Ra
- 下一篇: websocket python爬虫_p