How to check MongoDB connection status in D? - mongodb

As far as I understand from docs vibed have 2 was API for MongoDB
1. Low level
2. Hight level
Low level API have connection property, so I can connect to DB and check if connection is success with next code:
auto db = new MongoConnection("localhost", 27017);
db.connect;
if (db.connected == true)
writeln("Connected");
else
writeln("Can't connect to DB");
But all examples show that I need to use connect with Mongo with connectMongoDB class:
auto db = connectMongoDB("localhost").getDatabase("test");
but this class do not have connection status method.
Can I return from MongoConnection MongoClient type and use it's in my code. If I right understand all other methods need MongoClient to get basic operation.
Can I check connection status with connectMongoDB class?
Why try-catch block, do not avail? Even if I make an incorrect connectionString, I still can not get any error message.

Related

How wildfly resets properties set on connection when returned to connection pool

I am doing jndi lookup for datasource configured in JBOSS
DataSource dataSource = (DataSource) new InitialContext().lookup(dataSourceStr);
return dataSource.getConnection();
Connection is closed by using try-with-resource.
Once I get connection object I'm setting isolation property on it, I need it for my functionality.
connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);//1
Once my operation is done I want to check what's isolation value present in connection for that I created connection object using similar mechanism given above and tested it's value which I found as TRANSACTION_READ_COMMITTED(2) which is default one and not which I had overriden. This is actually working as I wanted it to. I've not reset value to TRANSACTION_READ_COMMITTED(2) again once my operation is done but still it's getting reset to original TRANSACTION_READ_COMMITTED(2) when returned backed to pool. I m interested in knowing how this is happening/where can I look for more details.
I have kept only 1 connection in connection pool so I know when I accessed connection again I got the same connection object on which I had previously overriden value TRANSACTION_READ_UNCOMMITTED for isolation. I double checked it's by not closing connection thus it gave error when I tried to access it again.
My question is how connection value which was overriden is getting reset when it's getting back to pool?
could you please post the configuration of you DataSource?
This Behaviour is not specified by JBoss/WildFly it depends on the Implementation of DS you are using. So the behavior you are seeing can change between vendor specific implementations of DataSources.
For example if you are using postgres you could have a look on github.com/pgjdbc/pgjdbc/blob/… this is the listener which is fired when a pooled connection is closed.. but it seems postgres doesn't have such an "reset" behavior of it's pooled connections

Flask -- Reloading database which was loaded before first request

I have an API run on flask which is connected to MongoDB and it uses this DB for reading only.
I connect to db before first request:
#app.before_first_request
def load_dicti():
c = MongoClient('mongodb://' + app.config['MONGO_DSN'], connect=False)
db = c.my_name
app.first, app.second = dictionary_compilation(db.my_base, another_dictionary)
However, this mongodb may be updated from time to time. My API doesn't know about it because this db was already loaded before first request.
What's the most efficient way to cope with it? I'd be grateful for explanations and code examples.
I don't quite figure out what you are going to do, but Application Context may be best practice. Just like demo in Flask docs, you could do:
def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'db'):
c = MongoClient('mongodb://' + app.config['MONGO_DSN'], connect=False)
g.db = c.my_name
return g.db
Then, you could use get_db() directly in your view function, mongdb will be conntected once only when there is no db attr in g.
If your connection is not that stable that you need to change it everytime, you could connect every request or every session.

How to use Cashbah MongoDB connections?

Note: I realise there is a similar question on SO but it talks about an old version of Casbah, plus, the behaviour explained in the answer is not what I see!
I was under the impression that Casbah's MongoClient handled connection pooling. However, doing lsof on my process I see a big and growing number of mongodb connections, which makes me doubt this pooling actually exists.
Basically, this is what I'm doing:
class MongodbDataStore {
val mongoClient = MongoClient("host",27017)("database")
var getObject1(): Object1 = {
val collection = mongoClient("object1Collection")
...
}
var getObject2(): Object2 = {
val collection = mongoClient("object2Collection")
...
}
}
So, I never close MongoClient.
Should I be closing it after every query? Implement my own pooling? What then?
Thank you
Casbah is a wrapper around the MongoDB Java client, so the connection is actually managed by it.
According to the Java driver documentation (http://docs.mongodb.org/ecosystem/drivers/java-concurrency/) :
If you are using in a web serving environment, for example, you should
create a single MongoClient instance, and you can use it in every
request. The MongoClient object maintains an internal pool of
connections to the database (default maximum pool size of 100). For
every request to the DB (find, insert, etc) the Java thread will
obtain a connection from the pool, execute the operation, and release
the connection. This means the connection (socket) used may be
different each time.
By the way, that's what I've experienced in production. I did not see any problem with this.

C# MongoDb Connect to Replica Set Issue

According to the mongodb website, I should be able to connect to a replica set if I just give it one member from the replica set:
"The C# Driver is able to connect to a replica set even if the seed list is incomplete. It will find the primary server even if it is not in the seed list as long as at least one of the servers in the seed list responds (the response will contain the full replica set and the name of the current primary)." http://www.mongodb.org/display/DOCS/CSharp+Driver+Tutorial#CSharpDriverTutorial-Connectionstrings
However, I cannot get my driver to connect if I just give it a secondary member.
This is my current connection statement:
m_server = MongoServer.Create(new MongoServerSettings { ConnectionMode = ConnectionMode.ReplicaSet, Server = new MongoServerAddress(connection) });
The 'connection' variable is: mongodb://servername/?safe=true
I saw this: https://jira.mongodb.org/browse/CSHARP-500, and I did run rs.status(), and did use the correct server name. Any help is appreciated!
At this moment I’m learning MongoDB and I’ve being playing around replica set connections. I like to contribute with 2 ways that I have used to connect to the database that I found useful, if doesn’t help anyone, at least I will have a place to refer to in the future (I’m sure I’m going to need it at some point)
first:
var connString = "mongodb://localhost:27029,localhost:27027,localhost:27028?connect=replicaSet";
var client = new MongoClient(connString);
var db = client.GetDatabase("test");
second:
var settings = new MongoClientSettings
{
Servers = new[]
{
new MongoServerAddress("localhost", 27027),
new MongoServerAddress("localhost", 27028),
new MongoServerAddress("localhost", 27029)
},
ConnectionMode = ConnectionMode.Automatic,
ReplicaSetName = "m101",
WriteConcern = new WriteConcern(WriteConcern.WValue.Parse("3"),wTimeout:TimeSpan.Parse("10"))
};
var client = new MongoClient(settings);
The first, allows me to connect to the database through the servers specified in the list of server. This allows the driver to connect automatically to the new principal node in the replica set in the case of failure with the principal.
With the second, I send the list of servers in the replica set, the connection type. The name of the replica set, and the write concern configuration. With this settings, I’m forcing the driver to wait for an acknowledge of writing from the 3 servers in the replica set (WValue:3) and to wait at the most 10 seconds for the confirmation of writing.
So, the connection variable is a full connection string, not something to pass to MongoServerAddress. Also, you can specify the connection mode on the connection string as well. Try this:
connection = "mongodb://servername/?safe=true&connect=replicaset";
m_server = MongoServer.Create(connectionString);

JDBC and ADO.Net: API comparison

What are the analogies between the objects found in JDBC and the ones found in ADO.Net?
I know the object model in JDBC and ADO.Net are not exactly the same, but I think some analogies can be found among them (and key differences worth stating).
That would be useful for those who knows one API and wants to learn the other, serving as a starting point maybe, or avoiding misunderstandings caused by assumptions one makes about the API that wants to learn.
e.g.: Which is the ADO.Net object that provides the same functionality/behavior as the JDBC ResultSet? the same for PreparedStatemes, and so on...
Here is a simple sequence for ADO.NET:
// 1. create a connection
SqlConnection conn = new SqlConnection(xyz)
// 2. open the connection
conn.Open();
// 3. create a command
SqlCommand cmd = new SqlCommand("select * from xyz", conn);
// 4. execute and receive the result in a reader
SqlDataReader rdr = cmd.ExecuteReader();
// 5. get the results
while (rdr.Read())
{
//dosomething
}
Here is a simple sequence for JDBC:
// 1. create a connection
Connection con = DriverManager.getConnection(xyz);
// 2. create a statement
Statement stmt = con.createStatement();
// 3. execute and receive results in a result set
ResultSet rs = stmt.executeQuery("SELECT * from xyz");
// 4. Get the results
while (rs.next())
{
// do something
}
And here is the analogy (ADO.NET => JDBC):
SqlConnection => Connection
SqlCommand => Statement
SqlDataReader => ResultSet
Not very thorough with jdbc, but from what I know ADO.NET follows a disconnected architecture, where a connection is established only for the time a query has to be executed or read. Once the reader is read, connection can be closed. The data caching are achieved using datasets and data adapters. In ADO.NET only one reader is allowed per connection. While disconnected architecture is certainly possible in jdbc, its built on the concept of having live connection where you can have multiple readers per connection.
Another difference in the API is that there is built in functionality in jdbc to get the last inserted id, while ADO lacks one.
Also read a nice comparison on data caching in ADO and jdbc.