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:

    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.3.0</version>
    </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);
    db.getCollection("restaurants").insertMany(places);
    // ====== To update a document.
    db.getCollection("restaurants").updateOne(
                        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>() {
       @Override
       public void apply(final Document document) {
          logger.info(document.toString());
       }
    });
    How to delete a collection in MongoDB with Java/Scala?
    // ===== To remove a collection.
    db.getCollection("restaurants").drop();