<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.13.1</version>
</dependency>
String remoteServerList = "mongodb://127.0.0.1:27017";
String database = "mydb";
MongoClientURI uri = new MongoClientURI(remoteServerList);
MongoClient mongoClient = new MongoClient(uri);
DB db = mongoClient.getDB(database);
mongoClient.close();
DBCollection coll = db.getCollection("testCollection");
mongoClient.setWriteConcern(WriteConcern.JOURNALED);
BasicDBObject doc = new BasicDBObject("name", "MongoDB")
.append("type", "database")
.append("count", 1)
.append("info", new BasicDBObject("x", 203).append("y", 102));
coll.insert(doc);
DBCollection collection = db.getCollection("testCollection");
Cursor results = collection.find();
while(results.hasNext()) {
DBObject result = results.next();
System.out.println(result);
}
db.getCollectionNames().forEach(tableName -> System.out.println(tableName));
db.getCollectionNames().forEach(tableName -> {
DBCollection collection = db.getCollection(tableName);
DBCursor cursor = collection.find();
while(cursor.hasNext()) {
BasicDBObject row = (BasicDBObject)cursor.next();
row.keySet().forEach(key -> {
Object value = row.get(key);
System.out.print(key + " |" + value + " |" + value.getClass() + ", ");
});
System.out.println();
}
System.out.println();
});