Java - Read & Write files from MongoDB with security

Github Project : example-java-read-and-write-from-mongodb-with-security

Common part

Maven Dependencies

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver</artifactId>
    <version>3.3.0</version>
</dependency>

MongoURI

Mongo URI are like that : mongodb://user:password@host:27017/database

Default port is 27017.

Connecting to a Mongo database with security

// ====== Connection to a MongoDB database with a user and a password
MongoClientURI mongoUri = new MongoClientURI(connectionUri);
MongoClient mongoClient = new MongoClient(mongoUri);
MongoDatabase db = mongoClient.getDatabase(mongoDatabase);

How to insert documents into Mongo with Java?

Code example

// ====== Inserting a list of BSON Documents in Mongodb
List<Document> places = Arrays.asList(restaurant1,restaurant2);
db.getCollection("restaurants").insertMany(places);

How to update a document in Mongo with Java?

// ====== Updating a Document
db.getCollection("restaurants").updateOne(
					new Document("_id",new ObjectId("57bea96d46e0fb000606c68c")),
					new Document("$set", new Document("address.street", "East 31st Street")));

How to query a document from Mongo with Java?

Code example

// ====== Finding Documents
FindIterable<Document> iterable = db.getCollection("restaurants").find();
iterable.forEach(new Block<Document>() {
   @Override
   public void apply(final Document document) {
      logger.info(document.toString());
   }
});