I do have a database named users but pymongo is looking for a db named as app is there any way to change to Pymongo connection method ?
this one is working if i crate a db named as app;
app = Flask(__name__)
mongo = PyMongo(app)
i want to connect like this but i do get an error for that ;
mongo = PyMongo('users')
I have found my answer;
client = MongoClient('localhost')
db = client['dbname']
collection = db.collection_name
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'dbname'
mongo = PyMongo(app)
This allows you to use flask_pymongo, more info here
Related
I am trying to connect with mongodb atlas from my flask app using flask-mongoengine.
DB_URI = "mongodb+srv://flask_app_user:flask_app_user#cluster0.6jwadcx5g.mongodb.net/flask_app?retryWrites=true&w=majority"
def create_app():
app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'replace_me_32437264278642')
app.config['MONGODB_SETTINGS'] = {
'host': os.environ.get('MONGODB_URI', DB_URI)
}
MongoEngine(app)
socketio.init_app(app)
SSLify(app)
return app
But I am getting an error,
pymongo.errors.InvalidURI: Invalid URI scheme: URI must begin with 'mongodb://'
How can I use mongo atlas with flask_mongoengine?
I don't want to stick with flask_mongoengine. I don't want to change that.
It worked correctly for me with the latest version flask_mongoengine-1.0.0 and pymongo-3.11.2
It seems you're using the host from MONGODB_URI env var...
What do you have in MONGODB_URI??
Could you share also which version are you using?
I am trying to connect my code to atlas mongo db but i get the error below,this is my code :
from pymongo import MongoClient
client = MongoClient("mongodb+srv://username:test#cluster0.yntdf.mongodb.net/test?
retryWrites=true&w=majority")
db = client["test"]
collection = db["test"]
collection.insert_one({"_id":0, "name": "hello", "score": 5})
i got the error:
ConfigurationError: A DNS label is empty.
Anyone know how to handle this error? I installed dnspython and pymongo
Your connection string is wrong. Double check it is correct and also the IP of the calling server is whitelisted.
I got the same issue, the following code works for me with python 3.9.1
import pymongo
import urllib
MONGODB_USERNAME = urllib.parse.quote_plus('test')
MONGODB_PASSWORD = urllib.parse.quote_plus('tset#000')
MONGODB_DATABASE = 'sampledb'
MONGODB_URL = "mongodb://"+MONGODB_USERNAME+":"+MONGODB_PASSWORD+"#cluster0.wq5js.mongodb.net/"+MONGODB_DATABASE+"?retryWrites=true&w=majority"
client = pymongo.MongoClient(MONGODB_URL)
In my web application, I use Flask as framework and MongoDB as persistent layer. There are multiple libraries to connect to MongoDB. I am currently using the low-level lib pyMongo. However, I would like to combine it with MongoEngine for some models.
The only approach I see is to create an instance of both clients. This looks a big doggy. Is there a simpler way to combine these libraries (pyMongo, MongoEngine) such that they use the same database (with different collections).
Its currently not possible to use an existing Pymongo client to connect MongoEngine but you can do the opposite; if you connect MongoEngine, you can retrieve its underlying pymongo client or database instances.
from mongoengine import connect, get_db, Document, StringField
conn = connect() # connects to the default "test" database on localhost:27017
print(conn) # pymongo.MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary())
db = get_db() # pymongo.Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary()), u'test')
print(db)
class Person(Document):
name = StringField()
coll = Person._get_collection()
print(coll) # pymongo.Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary()), u'test'), u'person')
Is it possible to connect to a remote MongoDB when using Jongo (jongo.org)?
I saw a piece of code where MongoClientURI was used like this:
MongoClientURI uri = new MongoClientURI("mongodb://IP_ADDRESS:27017/DB_NAME");
I have the following code:
if(client != null) {
db = client.getDatabase("StockApp");
database = client.getDB("StockApp");
jongo = new Jongo(database);
}
In this example, StockApp is the name of my database. It will connect to my local database (127.0.0.1:27017/StockApp). When I try to change StockApp to uri.getDatabase() in both lines, I get the following exception:
com.mongodb.MongoSocketOpenException: Exception opening socket
I can also see that it tries to connect to localhost (127.0.0.1).
When I change the uri to new MongoClientURI("IP_ADDRESS") or new MongoClientURI("IP_ADDRESS:27017) I get the error that the uri should start with mongodb://
Does anyone know if it is possible to connect to a remote MongoDB server using Jongo?
You can initialize Jongo from a MongoClient like this:
MongoClient mongoClient = new MongoClient("host", 27017);
DB db = mongoClient.getDB("theDB");
Jongo jongo = new Jongo(db);
You can check the MongoClient constructor detail here
I have a small connection routine which is as below:
val dbName = "myDb"
val user = "myUser"
val pass = "myPass"
val mongoDriver = new reactivemongo.api.MongoDriver()
val db = MyDBObject(
mongoDriver.connection(
Seq("XXXXX.mongolab.com:XXXXX"),
options = MongoConnectionOptions(authMode = ScramSha1Authentication),
authentications = List(Authenticate(dbName, user, pass))
),
dbName
)
I'm using this to create a new connection and then using this connection, I work with my documents. But the problem is that for some very strange reason, I could not get this to work!
Here is the error that I get:
CommandError[code=13, errmsg=not authorized on myDb to execute command {....,
code: BSONInteger(13)
}]
I've been trying to dig into this for almost 3 hours without any vail! The MongoLab uses 3.0 version of MongoDB and I use 0.11.7 version for the ReactiveMongo library.
Using the mongo shell, I'm able to log in to the MongoLab and create new collections with the same set of credentials!