简体   繁体   English

Pymongo MongoClient:如果您通过 URI 放入数据库,您如何将其取出?

[英]Pymongo MongoClient: if you put a database in via URI, how do you get it back out?

The documentation for MongoClient says that one may say 'host=' and give a full MongoDB URI. MongoClient的文档说,可以说“host=”并给出完整的 MongoDB URI。 Those include a database name.这些包括数据库名称。 Once I do that, is there some way to extract the db name from the MongoClient object?一旦我这样做了,有没有办法从 MongoClient 对象中提取数据库名称? I'm failing to spot it in the source code.我没有在源代码中发现它。

I believe what you are looking for can be found in pymongo.uri_parser .我相信你正在寻找的东西可以在pymongo.uri_parser找到。 In particular, look at the parse_uri function.特别是,看看parse_uri函数。 parse_uri takes a MongoDB URI as an argument and returns a dictionary containing values such as username , password and, most importantly, database . parse_uri将 MongoDB URI 作为参数并返回一个字典,其中包含usernamepassword以及最重要的database等值。

Example:例子:

from pymongo.uri_parser import parse_uri

mongo_uri = 'mongodb://james:brewer@localhost/test'

for k, v in parse_uri(mongo_uri).items():
    print k, ':', v

will print将打印

username : james
nodelist : [('localhost', 27017)]
database : test
connection : None
password : brewer
options : {}

Hope this helps!希望这可以帮助!

The MongoClient class has a method called get_default_database(default=None, [...other options...]) documented as: MongoClient类有一个名为get_default_database(default=None, [...other options...])记录为:

Get the database named in the MongoDB connection URI.获取在 MongoDB 连接 URI 中命名的数据库。

MongoClient also has a method called .get_database(name=None, [... other options...]) , where the name=None parameter is defined as: MongoClient还有一个方法叫做.get_database(name=None, [... other options...]) ,其中name=None参数定义为:

name (optional): The name of the database - a string. name(可选):数据库的名称 - 一个字符串。 If None (the default) the database named in the MongoDB connection URI is returned.如果没有(默认),则返回在 MongoDB 连接 URI 中命名的数据库。

So if all you have is the URI, but that URI contains a database name, You can get the MongoDB database like this:因此,如果您只有 URI,但该 URI 包含数据库名称,您可以像这样获取 MongoDB 数据库:

    mongo_database = pymongo.MongoClient(host=mongo_uri).get_default_database()

Or like this:或者像这样:

    mongo_database = pymongo.MongoClient(host=mongo_uri).get_database()

The default= parameter in the first method above and the name= parameter in the second perform the same function: allowing the application programmer to override the database named in the URI, or supplement it if one was not provided in the URI.上面第一个方法中的default=参数和第二个方法中的name=参数执行相同的功能:允许应用程序程序员覆盖 URI 中命名的数据库,或者如果 URI 中没有提供,则补充它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM