添加文檔
from pymongo import MongoClient
# 連接服務器
conn = MongoClient("localhost", 27017)
# 連接數(shù)據(jù)庫
db = conn.mydb
# 獲取集合
collection = db.student
#添加文檔
#collection.insert({"name":"abc", "age":19, "gender":1,"address":"北京", "isDelete":0})
collection.insert([{"name":"abc1", "age":19, "gender":1,"address":"北京", "isDelete":0},{"name":"abc2", "age":19, "gender":1,"address":"北京", "isDelete":0}])
#斷開
conn.close()
查詢文檔
import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId#用于ID查詢
# 連接服務器
conn = MongoClient("localhost", 27017)
# 連接數(shù)據(jù)庫
db = conn.mydb
# 獲取集合
collection = db.student
# 查詢文檔
# 查詢部分文檔
'''
res = collection.find({"age":{"$gt":18}})
for row in res:
? ? print(row)
? ? print(type(row))
'''
# 查詢所有文檔
'''
res = collection.find()
for row in res:
? ? print(row)
? ? print(type(row))
'''
#統(tǒng)計查詢
'''
res = collection.find({"age":{"$gt":18}}).count()
print(res)
'''
#根據(jù)id查詢
'''
res = collection.find({"_id":ObjectId("5995084b019723fe2a0d8d14")})
print(res[0])
'''
# 排序
'''
# res = collection.find().sort("age")#升序
res = collection.find().sort("age", pymongo.DESCENDING)
for row in res:
? ? print(row)
'''
# 分頁查詢
res = collection.find().skip(1).limit(1)
for row in res:
? ? print(row)
#斷開
conn.close()
更新文檔
from pymongo import MongoClient
# 連接服務器
conn = MongoClient("localhost", 27017)
# 連接數(shù)據(jù)庫
db = conn.mydb
# 獲取集合
collection = db.student
collection.update({"name":"lilei"},{"$set":{"age":25}})
#斷開
conn.close()
刪除文檔
from pymongo import MongoClient
# 連接服務器
conn = MongoClient("localhost", 27017)
# 連接數(shù)據(jù)庫
db = conn.mydb
# 獲取集合
collection = db.student
collection.remove({"name":"lilei"})
#全部刪除
collection.remove()
#斷開
conn.close()