警告:不要安裝“bson”包。PyMongo自帶bson軟件包,執(zhí)行“pip install bson”或“easy_install bson”會安裝與PyMongo不兼容的第三方軟件包。
一、安裝pymongo
1、用pip進行安裝
pip install pymongo
2、用easy_install進行安裝
easy_install pymongo
二、使用
在使用之前,確保已經(jīng)安裝了mongoDB
1、建立連接
import pymongo
mongo = pymongo.MongoClient('localhost',27017) #連接實例
db_test = mongo['test'] # 連接test庫
table_test=db_test['table_test']? #連接table_test表
2、插入一條數(shù)據(jù)
return_id=table_test.insert_one({'name':'測試名字','content':'測試內(nèi)容'})
3、插入一條數(shù)據(jù)并返回_id
return_id=table_test.insert_one({'name':'測試名字','content':'測試內(nèi)容'}).inserted_id
4、批量插入數(shù)據(jù)
data=[{ "name":"測試2", "content":"測試2" }, { "name":"測試3", "content":"測試4" }]
insert_all=table_test.insert_many(data)
5、批量插入數(shù)據(jù)并返回_id
insert_all=table_test.insert_many(data).inserted_ids
5、查詢一條數(shù)據(jù)
find_content = table_test.find_one({'name':'測試名字'})?
6、通過ObjectId查詢
注意:需在頂部引用from bson.objectid import ObjectId
find_content=table_test.find_one({'_id':ObjectId('5a4097b5c2ca13014c44ff48')})
7、查詢所有數(shù)據(jù)
for find in table_test.find():
? ? ? print(find)
8、計數(shù)
count = table_test.find().count()
9、添加索引
result=table_test.create_index([('name',pymongo.ASCENDING)],unique=True)
10、查看索引
result = sorted(list(table_test.index_information()))
11、刪除一條數(shù)據(jù)
result=table_test.delete_one({'name':'測試3'})
12、批量刪除
result=table_test.delete_many({'name':'測試2'})
13、修改一條數(shù)據(jù)
result=table_test.find_one_and_update({'name':'測試名字1'},{'$set':{'name':'1'}})
修改器:$set:例如把“測試名字1”修改成“1”
$unset:顧名思義,刪除,例如把“測試名字1”刪除,是把整個name字段刪除了,而不是把name字段的內(nèi)容清空
$inc: 增加已有鍵的值, 或者在鍵不存在時創(chuàng)建一個鍵,例如我的年齡是18歲,我想增加2歲,{'$inc':{'age':2}}
以上只是一些比較常用到的方法,如果有不明白的地方,可以給我留言。
python小白一只,歡迎各位大佬指點