Reputation: 837
I'm using mongoLabs
to host my database and I want to connect to it from my app.
I'm also using the Motor
module in pyMongo
. I'm unsure where to instantiate the connection.
For instance I know that if the database was on same local machine as the app I would do this:
database = motor.MotorClient().open_sync().myDatabase
The mongoLab site says to include the following uri
in the driver:
mongodb://<dbuser>:<dbpassword>@ds047057.mongolab.com:47057/myDatabase
But I cannot see how to create the connection to this database.
Thanks
Upvotes: 0
Views: 4470
Reputation: 741
Previous answers have got a bit outdated, so the correct way according to the docs and as worked for me:
import motor.motor_asyncio
import asyncio
from asyncio import coroutine
db = motor.motor_asyncio.AsyncIOMotorClient().database_name
https://motor.readthedocs.io/en/stable/tutorial-asyncio.html https://github.com/mongodb/motor/blob/master/doc/tutorial-asyncio.rst
Upvotes: 0
Reputation: 574
You should to specify connection settings for MotorClient following these manuals: MotorClient takes the same constructor arguments as MongoClient, as well as, http://emptysquare.net/motor/pymongo/api/motor/motor_client.html#motor.MotorClient, http://emptysquare.net/motor/pymongo/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient
"The host parameter can be a full mongodb URI, in addition to a simple hostname. It can also be a list of hostnames or URIs. Any port specified in the host string(s) will override the port parameter. If multiple mongodb URIs containing database or auth information are passed, the last database, username, and password present will be used. For username and passwords reserved characters like ‘:’, ‘/’, ‘+’ and ‘@’ must be escaped following RFC 2396."
db = database = motor.MotorClient('mongodb://<dbuser>:<dbpassword>@ds047057.mongolab.com:47057/myDatabase
').open_sync().myDatabase
Upvotes: 2
Reputation: 316
It looks like MotorClient takes the same arguments as MongoClient:
https://github.com/ajdavis/mongo-python-driver/blob/motor/motor/init.py#L782
http://api.mongodb.org/python/current/api/pymongo/mongo_client.html
Given that, you should be able to use the URI like so:
database = motor.MotorClient("mongodb://<dbuser>:<dbpassword>@ds047057.mongolab.com:47057/myDatabase").open_sync().myDatabase
Upvotes: 3