python操作MongoDB

205 阅读1分钟

一、添加文档

第一步:pip install pymongo

from pymongo import MongoClient

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

# 连接数据库
db = conn.mydb

# 获取集合
collection = db.student

# 添加文档
# 添加一个文档
# collection.insert({"name":"小明","age":22,"adress":"广州"})

#添加多个文档
res = collection.insert([{"name":"小红","age":11,"adress":"上海"},{"name":"大狗","age":50,"adress":"黑龙江"}])
print(res)
# 断开连接
conn.close()

二、查询文档

from pymongo import MongoClient

from bson.objectid import ObjectId

import pymongo

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

# 连接数据库
db = conn.mydb

# 获取集合
collection = db.student

# 查询文档
# 查询所有文档
# res = collection.find()
# for row in res:
#     print(row)

# 查询部分文档
res = collection.find({"age":{"$gte":22}})
for row in res:
    # print(row)
    # print(type(row))
    # 字典可以根据键值对取值
      print(row["age"])

# 统计查询
res = collection.find({"age":{"$gte":22}}).count()
print("查询数量为:"+str(res))

# 根据id查询(必须引入:from bson.objectid import ObjectId)
# res = collection.find({"_id":ObjectId("5fb31fe5fb330a5d184a812f")})
# print(res[0])

#查询指定的列
# “info”:1 :查询info字段的所有值("info":0  :则除了info字段都显示),
#_id:0不显示id值
         res = collection.find({},{"info":1,'_id':0})

# 查询结果排序

# 升序
# res = collection.find().sort("age")

# 降序(导包:import pymongo)

# res = collection.find().sort("age",pymongo.DESCENDING)
# for row in res:
#     print(row)

# 分页查询
# limit() 和skip()实现分页  :skip(3)表示跳过查到的前面三条,然后顺序取后面3条。
#  表示跳过第一页,拿第二页出来。
res = collection.find().skip(3).limit(3)
for row in res:
    print(row)

# 断开连接
conn.close()

三、更新文档

from pymongo import MongoClient

# 连接服务器
conn = MongoClient("localhost",27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student

# 更新文档

res = collection.update({"name":"小明"},{"$set":{"age":15}})
print(res["updatedExisting"])
# 断开连接
conn.close()

四、删除文档

from pymongo import MongoClient

# 连接服务器
conn = MongoClient("localhost",27017)
# 连接数据库
db = conn.mydb
# 获取集合
collection = db.student

# 删除文档
# 删除一个文档
res = collection.remove({"name":"大狗"})
print(res)

# 全部删除
# res = collection.remove()
# print(res)

# 断开连接
conn.close()