MongoDB Note9: 集群连接实例

MongoDB Note9: 集群连接实例

0. Tips

集群和单机连接基本一致,将端口号换为集群mongos的端口号即可。

1. Pymongo

from pymongo import MongoClient host = "192.168.92.145" port = 20000 # user_name = "demodb" # user_pwd = "password" # collection name db_name = "testdb" coll_name = 'table' mongo_conn = MongoClient( 'mongodb://{}:{}/?authSource={}'.format(host, port, db_name)) # 需要用的的表需要在认证后用client单独去关联 mongo_db = mongo_conn[db_name] mongo_coll = mongo_db[coll_name] # 获取所有collections并打印,验证是否登录成功 coll_names = mongo_db.list_collection_names(session=None) print(coll_names)

2. Mongoengine

''' Description: henggao_note version: v1.0.0 Date: 2022-04-28 20:09:23 LastEditors: henggao LastEditTime: 2022-04-29 19:53:40 ''' from mongoengine import * from datetime import datetime connect('testdb1', alias='db1', host="192.168.92.145", port=20000) class Categories(Document): ' 继承Document类,为普通文档 ' name = StringField(max_length=30, required=True) artnum = IntField(default=0, required=True) date = DateTimeField(default=datetime.now(), required=True) meta = {"db_alias": "db1", "collection": "permissao"} # 如果required为True则必须赋予初始值,如果有default,赋予初始值则使用默认值 cate = Categories(name="Linux") cate.save() # 保存到数据库