python淺學【網絡服務中間件】之MongoDB


一、關於MongoDB:

MongoDB 是由C++語言編寫的,是一個基於分布式文件存儲的開源數據庫系統。

在高負載的情況下,添加更多的節點,可以保證服務器性能。

MongoDB 旨在為WEB應用提供可擴展的高性能數據存儲解決方案。

MongoDB 將數據存儲為一個文檔,數據結構由鍵值(key=>value)對組成。MongoDB 文檔類似於 JSON 對象。字段值可以包含其他文檔,數組及文檔數組。

 

二、MongoDB的優勢:

  • MongoDB 的架構較少。它是一個文檔數據庫,它的一個集合持有不同的文檔。
  • 從一個到另一個的文檔的數量,內容和大小可能有差異。
  • MongoDB 中單個對象的結構很清淅。
  • MongoDB 中沒有復雜的連接。
  • MongoDB 提供深度查詢的功能,因為它支持對文檔的強大的動態查詢。
  • MongoDB 很容易擴展。
  • 它使用內部存儲器來存儲工作集,這是其快速訪問的原因。

 

三、MongoDB的簡單使用:

 

連接MongoDB shell:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

  • mongodb:// 這是固定的格式,必須要指定。

  • username:password@ 可選項,如果設置,在連接數據庫服務器之后,驅動都會嘗試登陸這個數據庫

  • host1 必須的指定至少一個host, host1 是這個URI唯一要填寫的。它指定了要連接服務器的地址。如果要連接復制集,請指定多個主機地址。

  • portX 可選的指定端口,如果不填,默認為27017

  • /database 如果指定username:password@,連接並驗證登陸指定數據庫。若不指定,默認打開 test 數據庫。

  • ?options 是連接選項。如果不使用/database,則前面需要加上/。所有連接選項都是鍵值對name=value,鍵值對之間通過&或;(分號)隔開

以下以windows為例:

PS D:\MongoDB\Server\4.2\bin> .\mongo.exe                                                      
MongoDB shell version v4.2.4-14-g88053fe                                                       
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb       
Implicit session: session { "id" : UUID("6dd2f853-83f7-4709-beea-0a78e3e49364") }              
MongoDB server version: 4.2.4-14-g88053fe                                                      
Server has startup warnings:                                                                   
2020-03-21T12:05:41.197+0800 I  CONTROL  [initandlisten]                                       
2020-03-21T12:05:41.197+0800 I  CONTROL  [initandlisten] ** WARNING: Access control is not enab
led for the database.                                                                          
2020-03-21T12:05:41.197+0800 I  CONTROL  [initandlisten] **          Read and write access to d
ata and configuration is unrestricted.                                                         
2020-03-21T12:05:41.197+0800 I  CONTROL  [initandlisten]                                       
---                                                                                            
Enable MongoDB's free cloud-based monitoring service, which will then receive and display      
metrics about your deployment (disk utilization, CPU, operation statistics, etc).              
                                                                                               
The monitoring data will be available on a MongoDB website with a unique URL accessible to you 
and anyone you share the URL with. MongoDB may use this information to make product            
improvements and to suggest MongoDB products and deployment options to you.                    
                                                                                               
To enable free monitoring, run the following command: db.enableFreeMonitoring()                
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()    
---                                                                                            
                                                                                                                                                                               
> show dbs  # 查看當前數據庫                                                                              
admin   0.000GB   # 數據庫帳號信息就存儲在admin數據庫                                                                            
config  0.000GB   # 存儲副本集的配置信息                                                                               
local   0.000GB   # 在本地存儲數據                                                                                
> use test  # 創建數據庫                                                                                
switched to db test                                                                            
> show dbs  # 查看數據庫發現沒有顯示,因為里面沒有數據                                                                               
admin   0.000GB                                                                              
config  0.000GB                                                                                
local   0.000GB                                                                             
> db.test.insert({'key':'value'})  # 插入數據                                                     
WriteResult({ "nInserted" : 1 })                                                               
> show dbs  # 再次查看數據庫,發現 test 數據庫顯示                                                                              
admin   0.000GB                                                                                
config  0.000GB                                                                                
local   0.000GB                                                                                
test    0.000GB                                                                                                                                                                                                                                                 
> db.test.drop()  # 刪除數據庫                                                                          
true                                                                                           
> show dbs                                                                                     
admin   0.000GB                                                                                
config  0.000GB                                                                                
local   0.000GB                                                                                
> db.createCollection('gather')  # 創建一個集合                                                          
{ "ok" : 1 }                                                                                   
> show collections  # 查看集合                                                                     
gather
> db.gather.insert({name:'riy',sex:'boy',mood:'haha'})  # 集合中插入數據                                     
WriteResult({ "nInserted" : 1 })
> db.gather.find()  # 查看集合數據                                                                
{ "_id" : ObjectId("5e787d761f3d1841d88ce3f1"), "name" : "riy", "sex" : "boy", "mood" : "haha" 
}
> db.gather.update({'sex':'boy'},{$set:{'sex':'girl'}})  # 修改集合中的數據                       
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })                              
> db.gather.find()                                                                             
{ "_id" : ObjectId("5e787d761f3d1841d88ce3f1"), "name" : "riy", "sex" : "girl", "mood" : "haha"
 }                                                                                                
> db.gather.drop()  # 刪除集合                                                                      
true                                                                                                                                                                              
                                                                                                                                                     

 

四、python簡單操作MongoDB:

安裝pymongo包: pip install pymongo

計算一個庫中所有的 collection 數

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:Riy


import pymongo


myclient = pymongo.MongoClient('mongodb://localhost:27017/')    # 創建連接
mydb = myclient["test"]  # 庫名
coll_names = mydb.list_collection_names()  # 獲取所有collection
k = 0
for i in coll_names:
    count = mydb[i].find().count()
    k += count
print(k)  # 計數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM