連接
# mongodb與python的交互
# pip3 intsall pymongo
import pymongo
from bson.objectid import ObjectId
#創(chuàng)建mongo客戶端鏈接
mongoConn = pymongo.MongoClient('localhost',27017)
# 第二種
# mongoConn = pymongo.MongoClient('mongodb://localhost:27017/')
#有賬號和密碼的連接
#mongoConn = pymongo.MongoClient('mongodb://user:paw@localhost:27017/')
#操作數(shù)據(jù)庫下的集合
#獲取要操作的數(shù)據(jù)庫
# use_db = mongoConn.數(shù)據(jù)庫名稱
use_db = mongoConn.mongotest
# use_db = mongoConn['mongotest']
#獲取數(shù)據(jù)庫下要操作的集合
use_col = use_db.class1804
# use_col = use_db['class1804']
文檔操作
增
def add_data():
document = {
# '_id':'2e761r27e1' 指定id
'name':'liyong',
'age':20,
'gender':'男',
'class':'1804',
}
document1 = {
'name':'lihua',
'age':22,
'gender':'男',
'class':'1804',
}
#插入單條(result直接返回一個id串)
# result = use_col.insert(document)
# use_col.insert_one(document)
#插入多條(result直接返回list(Object(...),Object(...))
result = use_col.insert([document,document1])
# use_col.insert_many([document,document1])
#也可以使用save
# use_col.save(document)
print(result)
刪
def delete_data():
#刪除一條
#result = use_col.delete_one({})
# result = use_col.remove({'name':'liyong'},multi=False)
# print(result)
#刪除多條
# result = use_col.delete_many({})
# multi=False刪除一條钩蚊,multi=True刪除多條,
result = use_col.remove({'name':'liyong'})
print(result)
改
def update_data():
#默認(rèn)情況下只修改一條
# result = use_col.update({'name':'liyong'},{'$set':{'age':23}})
# print(result)
#全文檔更新只修改一條
# result = use_col.update({'name':'liyong'},{'name':'lisi','age':23})
# print(result)
#更新超照到的全部結(jié)果修改多條
# result = use_col.update_many({'name':'liyong'},{'$set':{'age':23}})
# print(result)
# 使用save做更新操作,全文檔更新
#注意:name 'ObjectId' is not defined,導(dǎo)入Bson模塊下的objectid
result = use_col.save(
{'_id':ObjectId("5b836b9711575e79be9af0c7"),
'name':'wangwu'}
)
查
def find_data():
# 使用find查詢钻注,會返回一個cursor?qū)ο螅? #<pymongo.cursor.Cursor object at 0x7fa13d988e10>
# 我們要拿到數(shù)據(jù)会宪,需要遍歷
# result = use_col.find({'name':'liyong'})
# print(result)
# print([i for i in result])
# result = use_col.find_one_and_delete()
# result = use_col.find_one_and_replace()
# result = use_col.find_one_and_update()
#find_one查詢時撬陵,直接返回一個字典
# result = use_col.find_one({'name':'liyong'})
# print(result)
# print(type(result))
#跳過和限制查詢s
# result = use_col.find({}).limit(4).skip(2).sort([("age",1),("name",1)])
result = use_col.find({}).limit(4).skip(2).sort("age",1).sort("name",1)
print([i for i in result])
# for dict in result:
# print(dict)
if __name__ == '__main__':
# add_data()
# update_data()
# find_data()
# delete_data()