# pip install pymongo
from pymongo import MongoClient
# 假设你的MongoDB集群地址是 "mongodb://user:password@host1:port1,host2:port2,host3:port3"
# 其中,user 和 password 是集群的认证信息,host1, host2, host3 是集群中节点的地址,port1, port2, port3 是对应节点的端口号
connection_string = "mongodb+srv://test:xxxxxx@psmdb-db-rs0.operation.svc.cluster.local/test?replicaSet=rs0&ssl=false"
client = MongoClient(connection_string, serverSelectionTimeoutMS=5000)
try:
"""
# print(client.server_info()) # 输出服务信息
# 选择数据库和集合
db = client['test']
collection = db['test']
# 进行查询操作
query = {'test': 'test'}
results = collection.find(query)
#增加一条
stu1={'id':'001','name':'zhangsan','age':10}
result = collection.insert_one(stu1)
#增加多条
stu2={'id':'002','name':'lisi','age':15}
stu3={'id':'003','name':'wangwu','age':20}
result = collection.insert_many([stu2,stu3])
#可以直接使用remove方法删除指定的数据
result = collection.remove({'name': 'zhangsan'})
#使用delete_one()删除一条数据
result = collection.delete_one({"name":"zhangsan"})
#delete_many()删除多条数据
result = collection.delete_many({"age":{'$lt':20}})
#update_one,第 2 个参数需要使用$类型操作符作为字典的键名
#姓名为zhangsan的记录,age修改为22
condition = {'name': 'zhangsan'}
res = collection.find_one(condition)
res['age'] = 22
result = collection.update_one(condition, {'$set': res})
print(result) #返回结果是UpdateResult类型
print(result.matched_count,result.modified_count) #获得匹配的数据条数1、影响的数据条数1
#update_many,所有年龄为15的name修改为xixi
condition = {'age': 15}
res = collection.find_one(condition)
res['age'] = 30
result = collection.update_many(condition, {'$set':{'name':'xixi'}})
print(result) #返回结果是UpdateResult类型
print(result.matched_count,result.modified_count) #获得匹配的数据条数3、影响的数据条数3
# 查询数据
rets = collection.find({"age":20})
for ret in rets:
print(ret)
# 查询结果有多少条数据
count = collection.find().count()
# 查询结果按年龄升序排序
results = collection.find().sort('age', pymongo.ASCENDING)
print([result['age'] for result in results])
"""
# 选择数据库和集合
db = client['test']
collection = db['test']
# 进行查询操作
query = {'test': 'test'}
results = collection.find(query)
for document in results:
print(document)
except Exception as e:
print("无法连接到MongoDB服务", e) # 提示异常