Java Driver for MongoDB
MongoDB provides two official drivers for Java - the sync driver and the reactive streams driver. The sync driver is used for most purposes.
Not every MongoDB driver version has been tested with every MongoDB server version. The compatibility matrix for the drivers, the server version, and the Java runtime version is at: https://docs.mongodb.com/drivers/java/sync/current/compatibility/
Next, if you are using Maven, add the driver dependency to the pom.xml, as follows:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.4.1</version>
</dependency>
To do any kind of CRUD on MongoDB, you need to get a reference to a MongoCollection
object… through a MongoDatabase object… which needs a MongoClient
object. So, here’s a quick way to get a collection object:
MongoClient client = MongoClients.create("mongodb://.......")
MongoDatabase db = client.getDatabase("test")
MongoCollection boatsCollection = db.getCollection("boats")
For more about the mongodb:// URI, read more about connection string URIs and SRV records.
Another way to get a MongoClient
object is by specifying the database server connection through code instead of through the URI:
MongoCredential credential = MongoCredential.createCredential(user, database, password);
MongoClientSettings settings = MongoClientSettings.builder()
.credential(credential)
.applyToSslSettings(builder -> builder.enabled(true))
.applyToClusterSettings(builder ->
builder.hosts(Arrays.asList(new ServerAddress("host1", 27017))))
.build();
MongoClient mongoClient = MongoClients.create(settings);
The next couple of code snippets briefly demonstrate the use of the MongoDB driver…
To use builders to create queries:
import static com.mongodb.client.model.Filters.*;
MongoIterable<Document> results = boatsCollection.find(
and(
eq("name", "MSC Daniela"),
or (
eq("size", "Unknown"),
eq("size", "Not Recorded")
)
)
);
Fetching data from an iterator
movies.find().iterator().tryNext() //returns a Document instance
//tryNext - returns null instead of exception (next)
You have to know how to work the Document
class:
Document doc = new Document("name", "MSC Daniela")
.append("size", "Unknown");
HashMap<String, Object> properties = HashMap<String, Object>();
properties.put("key", value");
doc.putall( properties );
Also, note that the order of fields matters:
Document doc = new Document("field1", "value1")
.append("field2", "value2");
Document parentDoc = new Document("parentField", doc);
/*
{
parentField: {
field1: value1,
field2, value2
}
}
*/
Document doc2 = new Document("field2", "value2")
.append("field1", "value1");
Document parentDoc2 = new Document("parentField", doc2);
/*
{
parentField: {
field2, value2,
field1: value1
}
}
*/
coll.insertOne(parentDoc);
coll.insertOne(parentDoc2);
Upon inserting a document without specifying an _id
, we get an ObjectID
generated and we can fetch the _id
value:
//Inserting one document
InsertOneResult result1 = insert_test.insertOne(parentDoc1);
//Either use .getInsertedId()
ObjectId insertedId1 = result1.getInsertedId().asObjectId().getValue();
//...or fetch it from the Document object that was passed to insertOne
Object parentDoc1Id = parentDoc1.get("_id");
//Inserting multiple documents
InsertManyResult insertResult = insert_test.insertMany(Arrays.asList(parentDoc1, parentDoc2));
//Either use .getInsertedIds()
Map<Integer, BsonValue> resultIds = insertResult.getInsertedIds();
//...or fetch them from the Documents object that was passed to insertMany
Object parentDoc1Id = parentDoc1.get("_id");
Object parentDoc2Id = parentDoc2.get("_id");
When explicitly setting the _id
value, inserting duplicates throws the MongoWriteException
(E11000 duplicate key error ….) because the _id
field has a unique index defined.