Reputation: 671
I am using the following mongodb driver.
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.0.2</version>
</dependency>
Here's how I connect
String textUri = "mongodb://<username>:<password>@ds027155.mlab.com:27155/";
MongoClientURI uri = new MongoClientURI(textUri);
MongoClient m = new MongoClient(uri);
I get the error. However if I mention database name
String textUri = "mongodb://<username>:<password>@ds027155.mlab.com:27155/<db-name>";
It works without any issue.. Acutally I want to list all the databases present on the server. How do I do I mention uri without specifying the database name?
Also how do I list only user defined collections present in the DB.
MongoDatabase db = m.getDatabase("standupmeetingnotes");
ListCollectionsIterable<Document> listColl = db.listCollections();
MongoIterable<String> colls = db.listCollectionNames();
for (String s : colls) {
System.out.println(s);
}
It prints objectlabs-system, objectlabs-system.admin.collections, system.indexes also which are system defined collections apart from user defined ones.
Any way I will be able to omit those?
Thanks.
Upvotes: 0
Views: 3510
Reputation: 1988
Answering the question in the topic: "How to get connect to MongoDB in Java without specifying it database name in the URL?". I've created simple class to connect to the MongoDB using API 3.2.2. and read list of the databases.
Apparently, there are two ways to connect to the MongoDB instance -- with URL and without URL. In previous versions there was way to connect to the DB (within instance) with username and password without URL either, but afaik, in 3.2.2 it is no longer possible. (I should admit, the pace at which MongoDB team changes their Java API is truly remarkable.)
Anyways, the class works equally with and without username/password (provided the access to the Mongo w/o password is possible at all). And the DB connect step can be executed at the later time, after connection established.
package testmongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import java.util.LinkedList;
import java.util.List;
public class MongoConnector {
private final MongoClient mongoClient;
private MongoDatabase db;
public MongoConnector(String host, int port)
{
this.mongoClient = new MongoClient(host, port);
}
public MongoConnector(String host, int port, String username, String password)
{
String textUri = "mongodb://"+username+":"+password+"@"+host+":"+port;
MongoClientURI uri = new MongoClientURI(textUri);
this.mongoClient = new MongoClient(uri);
}
public boolean connectToDB(String dbName)
{
this.db = mongoClient.getDatabase(dbName);
return this.db != null;
}
public List<String> listAllDB()
{
List<String> ret = new LinkedList<>();
MongoIterable<String> x = mongoClient.listDatabaseNames();
for(String t : x)
{
ret.add(t.toString());
}
return ret;
}
}
Upvotes: 1