python中mongodb怎么连接其他服务器的数据库

2024-11-27 00:28:36
推荐回答(2个)
回答1:

1、基于mongo实现远程连接

[plain] view plaincopy

mongo -u admin -p admin 192.168.0.197:27017/pagedb

通过mongo实现连接,可以非常灵活的选择参数选项,参看命令帮助,如下所示:

[plain] view plaincopy

mongo --help
MongoDB shell version: 1.8.3
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
foo foo database on local machine
192.169.0.5/foo foo database on 192.168.0.5 machine
192.169.0.5:9999/foo foo database on 192.168.0.5 machine on port 9999
options:
--shell run the shell after executing files
--nodb don't connect to mongod on startup - no 'db address'
arg expected
--quiet be less chatty
--port arg port to connect to
--host arg server to connect to
--eval arg evaluate javascript
-u [ --username ] arg username for authentication
-p [ --password ] arg password for authentication
-h [ --help ] show this usage information
--version show version information
--verbose increase verbosity
--ipv6 enable IPv6 support (disabled by default)

2、基于MongoDB支持的javascript实现远程连接

当你已经连接到一个远程的MongoDB数据库服务器(例如,通过mongo连接到192.168.0.184),现在想要在这个会话中连接另一个远程的数据库服务器(192.168.0.197),可以执行如下命令:

[plain] view plaincopy

> var x = new Mongo('192.168.0.197:27017')
> var ydb = x.getDB('pagedb');
> use ydb
switched to db ydb
> db
ydb
> ydb.page.findOne()
{
"_id" : ObjectId("4eded6a5bf3bfa0014000003"),
"content" : "巴黎是浪漫的城市,可是...",
"pubdate" : "2006-03-19",
"title" : "巴黎:从布鲁塞尔赶到巴黎",
"url" : "http://france.bytravel.cn/Scenery/528/cblsegdbl.html"
}

上述通过MongoDB提供的JavaScript脚本,实现对另一个远程数据库服务器进行连接,操作指定数据库pagedb的page集合。

如果启用了安全认证模式,可以在获取数据库连接实例时,指定认证账号,例如:

[plain] view plaincopy

> var x = new Mongo('192.168.0.197:27017')
> var ydb = x.getDB('pagedb', 'shirdrn', '(jkfFS$343$_\=\,.F@3');
> use ydb
switched to db ydb

回答2:

对于mongo的操作,先安装mongodb的python扩展,在你的命令行窗口上输入:pip install pymongo,下面是例子,按需要修改

from pymongo import MongoClientimport timemongo_uri_auth = 'mongodb://user:password@localhost:27017/'#mongo有要验证的话请自行替换user和passwordmongo_uri_no_auth = 'mongodb://localhost:27017/' #mongo没有账号密码验证的时候用这个database_name = 'request_db' # 你要连接的数据库名,自行替换你需要的库名table_name = 'request_tb' #你要查询的表名,请自行替换你需要的表名client = MongoClient(mongo_uri_no_auth)#创建了与mongodb的连接db = client[database_name]table = db[table_name] #获取数据库中表的游标#你要插入的数据insert_data = {"name": "Mike", "grade": "two", "age": 12, "sex": "man"}table..insert_one(insert_data ) #插入一条数据#查询数据name为Mike的记录record = table.find_one({"name": "Mike"})print record