Last active
April 1, 2020 16:24
-
-
Save pracps/3d8780e101a679abaf6a349e013664d9 to your computer and use it in GitHub Desktop.
Sample Mongo java client using replica set
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const MongoClient = require('mongodb').MongoClient; | |
const assert = require('assert'); | |
// Connection URL | |
const user = encodeURIComponent('username'); | |
const password = '************'; | |
const url = `mongodb://${user}:${password}@d7mongo41.company.com:27017,d7mongo41.company.com:27018,d7mongo41.company.com:27019/?authSource=dome&replicaSet=rs0`; | |
//const url = `mongodb://${user}:${password}@d7mongo41.company.com:27017?authSource=admin`; | |
console.log(url); | |
const dbName = 'somedb'; | |
const client = new MongoClient(url, {useNewUrlParser: true}); | |
client.connect(function(err) { | |
assert.equal(err, null); | |
console.log("Connected successfully to server"); | |
const db = client.db(dbName); | |
db.listCollections().toArray(function(err, collInfos) { | |
console.log(collInfos); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.mongodb.MongoClientURI; | |
import com.mongodb.MongoClient; | |
import com.mongodb.client.MongoDatabase; | |
/** | |
* Download driver: | |
* https://repo1.maven.org/maven2/org/mongodb/mongo-java-driver/3.8.1/mongo-java-driver-3.8.1.jar | |
* Compile: | |
* javac -cp ".:./mongo-java-driver-3.8.1.jar" MongoTest.java | |
* Run | |
* java -cp ".:./mongo-java-driver-3.8.1.jar" MongoTest | |
*/ | |
public class MongoTest { | |
public static void main(String[] args) { | |
String MONGO_HOST = "host.domain.com"; | |
String MONGO_AUTH_DB = "auth_db_like_admin"; | |
String AUTH_USER = "username"; | |
String AUTH_PASSWORD = "password"; | |
MongoClientURI uri = new MongoClientURI("mongodb://" + AUTH_USER + ":" + AUTH_PASSWORD + "@" + MONGO_HOST + ":27017," + MONGO_HOST + ":27018," + MONGO_HOST + ":27019/" + MONGO_AUTH_DB + "?replicaSet=rs0"); | |
MongoClient mongoClient = new MongoClient(uri); | |
MongoDatabase database = mongoClient.getDatabase(MONGO_AUTH_DB); | |
for (String name : database.listCollectionNames()) { | |
System.out.println(name); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment