MongoDB
是由C++
語言編寫的非關系型數據庫,是一個基于分布式文件存儲的開源數據庫系統,其內容存儲形式類似JSON
對象,它的字段值可以包含其他文檔、數組及文檔數組。在這一節中,我們就來回顧Python 3
下MongoDB
的存儲操作。
常用命令:
-
查詢數據庫:
show dbs
-
使用數據庫:
use 庫名
-
查看集合:
show tables/show collections
-
查詢表數據:
db.集合名.find()
-
刪除表:
db.集合名.drop()
鏈接MongoDB
連接MongoDB
時,我們需要使用PyMongo
庫里面的MongoClient
。一般來說,傳入MongoDB
的IP
及端口即可,其中第一個參數為地址host
,第二個參數為端口port
(如果不給它傳遞參數,默認是27017)
import pymongo # 如果是云服務的數據庫 用公網IP連接client = pymongo.MongoClient(host='localhost', port=27017)
指定數據庫與表
import pymongoclient = pymongo.MongoClient(host='localhost', port=27017)collection = client['students']
插入數據
對于students
這個集合,新建一條學生數據,這條數據以字典形式表示:
# pip install pymongoimport pymongomongo_client = pymongo.MongoClient(host='localhost', port=27017)collection = mongo_client['students']['stu_info']# 插入單條數據# student = {'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}# result = collection.insert_one(student)# print(result)# 插入多條數據student_1 = {'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male'}student_2 = {'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}result = collection.insert_many([student_1, student_2])print(result)