Read and Write Files From MongoDB With Java/Scala
-
Install the following Maven dependency:
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver</artifactId> <version>3.3.0</version> </dependency>
-
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/
, where27017
is the default port. -
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:
// ====== 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();