Pymodm connect to an mlab MongoDB - mongodb

I have a MongoDB database hosted on mlab and I would like to use PyMODM as my object modeling library.
This is my code so far:
from pymodm import connect, MongoModel, fields
connect = connect('mongodb://user:pass#ds119788.mlab.com/db')
class Test(MongoModel):
user = fields.CharField()
if __name__ == "__main__":
test = Test("test")
test.save()
But it gives me this error :
pymongo.errors.ServerSelectionTimeoutError: ds119788.mlab.com:27017: [Errno 61] Connection refused
Am I missing something?

You need to use the MongoDB URI provided by mlab for your account. The URI should contain the port number to connect to.
For example, it should look like :
connect = connect('mongodb://user:password#ds119788.mlab.com:63123/databaseName')

Related

how to connect atlas mongodb with a cluster

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)

Combine MongoDb clients: pyMongo and MongoEngine

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')

Connect to MongoDB Atlas with mongo_dart

I try to connect to a MongoDB Atlas database through mongo_dart with this line of code. The provided link from MongoDB is defined by:
mongodb+srv://<user>:<PASSWORD>#test-asdf.mongodb.net/test?retryWrites=true
throws an "Invalid scheme" Error. When I cut out "+srv" and try to connect with:
Db db = new Db("mongodb://<user>:<password>#test-asdf.mongodb.net/test?retryWrites=true");
it throws a SocketException: Failed host lookup.
Is it even possible to access to a atlas mongoDB or am I forgetting something?
The mongodb+srv:// protocol is for new driver, maybe you can try to click the button "I am using driver 3.4 or earlier" to get the legacy url with mongodb:// protocol
In order to connect to atlas, you need to pass connection string which connect your atlas to mongo_dart like this:
import "package:mongo_dart/mongo_dart.dart;
void getConnection() async {
String connectionString = "mongodb+srv://<user>:<password>#test-asdf.mongodb.net/test?retryWrites=true&w=majority";
print(connectionString);
// Connect to database:
Db db = await Db.create(connectionString);
await db.open();
print(db);
}

Database 'height_collector' does not exist! Python flask

When i am trying to connect to my existing database(it is realy exist) i have an ERROR occur:
Here is my code and error:
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:postgres510#localhost/height_collector'
db = SQLAlchemy(app)
class Data(db.Model):
__tablename__ = "data"
id = db.Column(db.Integer, primary_key=True)
email_ = db.Column(db.String(120), unique=True)
height_ = db.Column(db.Integer)
def __init__(self, email_, height_):
self.email_ = email_
self.heigth_ = height_
#app.route("/")
def index():
return render_template("index.html")
#app.route("/success", methods=['post'])
def success():
if request.method == 'POST':
email = request.form["email_name"]
height = request.form["height_name"]
print(email, height)
return render_template("success.html")
if __name__ == '__main__':
app.debug = True
app.run()
and then i have an error
Data base ".." doesn't exist!
Here is a picture of my database
It's hard to be sure, but this is probably related to either network names, postgres server config, or permissions.
You need to go through different possibilities step by step and eliminate them as the cause. You can connect and see the db in pgAdmin, and you can't connect in Flask. Somewhere between these two is a difference which stops it from working.
Double-check that in pgAdmin you can correctly open the database which you see pictured and look at the tables (if any). It could be that pgAdmin is showing this db open but it isn't connectable any more.
Can you make sure that in pgAdmin, you use localhost as the host name of your connection, and not the IP address of the machine or anything else. If this is the problem, you need to look at how postgres is configured, and in particular the listen key in the postgres config. If listen is set to localhost, you should be good.
I don't see where you mentioned that you are using Windows, but another answerer seems to have assumed this, is this the case? Does the command ping localhost in a shell succeed?
Connect in pgAdmin using the exact user and password that you use in your Flask code.
Try to connect in Python, not in Flask. Open a Python shell, import psycopg2 and call psycopg2.connect(host='localhost', user='postgres', ...)

How can I write a query to connect mongodb?

I have installed mongodb in different server. I have modified my old code
db: 'mongodb://localhost/dev',
to new code
my username : proUseAdd
password : mongodb#23
ip : 169.213.64.127
I modified like this
db: 'mongodb://proUseAdd:mongodb#23#169.213.64.127:27017/dav',
I am getting this error
Could not connect to MongoDB!
Error: failed to connect to
[23#169.213.64.127:27017]
UPDATE
i have tried changed my password:mongodb23
query strin:
db: 'mongodb://proUseAdd:mongodb23#169.213.64.127:27017/dav',
still i'm getting error
Could not connect to MongoDB!
Error: failed to connect to
[169.213.64.127:27017]
Change your password to something which doesn't contain #.
While parsing your connection string, MongoDB driver looks for the # character to separate your credentials and the host name. Since your password has an # in it, it recognizes your credentials as proUseAdd:mongodb and your host name as 23#169.213.64.127:27017.