python 连接mongodb跨数据库查询

时间:2024-05-22 22:51:53

在使用mongodb的时候,遇到一个这样的情况,连接数据库的时候,使用的是admin 数据库,但是我需要查询的是 另一个数据库test-msc-db ,这里涉及到跨库查询。
比如:
python 连接mongodb跨数据库查询
那么,这里涉及到跨库查询,具体脚本如下:

from pymongo import MongoClient
from buisness.GetToken import GetToken
from util.readConfig import ReadConfig
import pymongo
myclient = pymongo.MongoClient("mongodb//root:[email protected]:27017/")
mydb = myclient[admin]   #连接数据库的时候,使用的是 admin 数据库
mydb.authenticate(self.username, self.passwd)
my_db=myclient["test-msc-db"]    #test-msc-db是需要查询的数据库
mydb.authenticate('root','123456')
mycol = my_db["customer_refund"]    #customer_refund是数据库test-msc-db的中一个数据表
for x in mycol.find({"Id":"80","testId":"1375"}):
  print(x)

习惯了Python,在更多测试的工作中,都想着使用python,应用起来很是方便,省时间。
每到一个新项目,都会涉及到各种新知识,也是学习,扩展丰富知识面的最好机会。

有关更多的python mongodb 使用,可以加好友
python 连接mongodb跨数据库查询