python连接Mongodb

python连接Mongodb

  1. 安装依赖包
    • pip instal pymongo
  2. 创建python文件
    • from pymongo import MongoClient
    • 创建Client客户端 client = MongoClient(“mongo://host:port”)
    • 可以通过client获取数据库 db = client[“Learn”]
    • 可以通过db获取集合 col = db[“person”]
    • 通过集合就可以操作数据了,增删改查,
    • 查询出来的数据都是cursor,游标,数据集合,可以通过循环进行迭代
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
database = client["learn"]
collection = database["people"]

# Created with Studio 3T, the IDE for MongoDB - https://studio3t.com/

query ={}
query['age']=33

cursor = collection.find(query)
# 捕获异常
try:
    for doc in cursor:
        print(doc["name"])
#释放资源
finally:
    cursor.close()

你可能感兴趣的:(mongodb)