Read and Write Files From MongoDB With Java/Scala

How to read and write files from MongoDB with Java/Scala.

  1. Install the following Maven dependency:

  2. Connect to a MongoDB database with security by running the following lines of code:

    // ====== To connect to a MongoDB database with a user and a password.
    String connectionUri = "mongodb://user:password@host:27017/";
    MongoClientURI mongoUri = new MongoClientURI(connectionUri);
    MongoClient mongoClient = new MongoClient(mongoUri);
    MongoDatabase db = mongoClient.getDatabase(mongoDatabase);
    The MongoDB connection URL format must be mongodb://user:password@host:27017/ where 27017 is the default port.
  3. You can now insert and update a document in MongoDB, as well as query a document from MongoDB by running the following lines of code:

    • Insert Documents in MongoDB

    • Update Documents in MongoDB

    • Query Documents From MongoDB

    // ====== To insert a list of BSON documents in MongoDB.
    List<Document> places = Arrays.asList(restaurant1,restaurant2);
    // ====== To update a document.
                        new Document("_id",new ObjectId("57bea96d46e0fb000606c68c")),
                        new Document("$set", new Document("address.street", "East 31st Street")));
    // ====== To find documents.
    FindIterable<Document> iterable = db.getCollection("restaurants").find();
    iterable.forEach(new Block<Document>() {
       public void apply(final Document document) {
    How to delete a collection in MongoDB with Java/Scala?
    // ===== To remove a collection.