1,添加文档

需要先安装下三方库 pip install pymongo

from pymongo import MongoClient


#连接服务器
conn = MongoClient("localhost",27017)

#连接数据库

db = conn.mydb

#获取集合

collection = db.student

#添加文档

#collection.insert({"name":"lilei2","age":19,"gender":1,"address":"北京","inDelete":0})
collection.insert([{"name":"abc1","age":19,"gender":1,"address":"北京","inDelete":0},{"name":"abc2","age":19,"gender":1,"address":"北京","inDelete":0}])

#断开
conn.close()

2,查询文档

from pymongo import MongoClient
from bson.objectid import ObjectId  #用于ID查询
import pymongo

#连接服务器
conn = MongoClient("localhost",27017)

#连接数据库

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))

print("-----------统计查询-----------")
#统计查询
'''
res = collection.find({"age":{"$gt":18}}).count()
print(res)
'''

#根据id查询
print("-----------根据ID查询------------")

res = collection.find({"_id":ObjectId("5ecae84d120cbce3cecfd52f")})
print(res)
print(res[0])


#排序
print("-----------排序------------")
res = collection.find().sort("age") #升序
print("-----------降序--------------") #降序
res = collection.find().sort("age",pymongo.DESCENDING)

for row in res:
    print(row)
    print(type(row))

#分页

print("                 ---------------分页------------------")
res = collection.find().skip(3).limit(5)

for row in res:
    print(row)
    print(type(row))


#断开
conn.close()

3, 更新文档

from pymongo import MongoClient


#连接服务器
conn = MongoClient("localhost",27017)

#连接数据库

db = conn.mydb

#获取集合

collection = db.student
#更新文档
collection.update({"name":"lilei"},{"$set":{"age":25}})

#断开
conn.close()

4,删除文档

from pymongo import MongoClient


#连接服务器
conn = MongoClient("localhost",27017)

#连接数据库

db = conn.mydb

#获取集合

collection = db.student
#删除文档

collection.remove({"name":"lilei1"})
#全部删除
#collection.remove()

#断开
conn.close()
Last modification:July 1st, 2020 at 04:14 am
如果觉得我的文章对你有用,请随意赞赏