The MongoDB Synchronous Driver for Java providing blocking I/O patterns for database operations
—
The MongoCollection interface provides comprehensive CRUD (Create, Read, Update, Delete) operations for working with MongoDB collections. This document covers all available operations with detailed examples and configuration options.
Inserts a single document into the collection.
InsertOneResult insertOne(TDocument document)
InsertOneResult insertOne(TDocument document, InsertOneOptions options)
InsertOneResult insertOne(ClientSession clientSession, TDocument document)
InsertOneResult insertOne(ClientSession clientSession, TDocument document, InsertOneOptions options)Parameters:
clientSession - Client session for transaction supportdocument - The document to insertoptions - Insert options (bypass document validation, etc.)Usage Examples:
// Basic insert
Document doc = new Document("name", "John Doe")
.append("email", "john@example.com")
.append("age", 30);
InsertOneResult result = collection.insertOne(doc);
ObjectId insertedId = result.getInsertedId().asObjectId().getValue();
// Insert with options
InsertOneOptions options = new InsertOneOptions()
.bypassDocumentValidation(true);
collection.insertOne(doc, options);
// Insert with session (for transactions)
try (ClientSession session = mongoClient.startSession()) {
collection.insertOne(session, doc);
}Inserts multiple documents into the collection.
InsertManyResult insertMany(List<? extends TDocument> documents)
InsertManyResult insertMany(List<? extends TDocument> documents, InsertManyOptions options)
InsertManyResult insertMany(ClientSession clientSession, List<? extends TDocument> documents)
InsertManyResult insertMany(ClientSession clientSession, List<? extends TDocument> documents, InsertManyOptions options)Parameters:
clientSession - Client session for transaction supportdocuments - List of documents to insertoptions - Insert options (ordered, bypass document validation)Usage Examples:
// Basic batch insert
List<Document> documents = Arrays.asList(
new Document("name", "Alice").append("age", 25),
new Document("name", "Bob").append("age", 30),
new Document("name", "Charlie").append("age", 35)
);
InsertManyResult result = collection.insertMany(documents);
Map<Integer, BsonValue> insertedIds = result.getInsertedIds();
// Unordered insert (continue on error)
InsertManyOptions options = new InsertManyOptions()
.ordered(false)
.bypassDocumentValidation(true);
collection.insertMany(documents, options);
// Insert with session
try (ClientSession session = mongoClient.startSession()) {
collection.insertMany(session, documents);
}Retrieves documents from the collection with optional filtering, sorting, and projection.
FindIterable<TDocument> find()
FindIterable<TDocument> find(Bson filter)
FindIterable<TDocument> find(ClientSession clientSession)
FindIterable<TDocument> find(ClientSession clientSession, Bson filter)
<TResult> FindIterable<TResult> find(Class<TResult> resultClass)
<TResult> FindIterable<TResult> find(Bson filter, Class<TResult> resultClass)
<TResult> FindIterable<TResult> find(ClientSession clientSession, Class<TResult> resultClass)
<TResult> FindIterable<TResult> find(ClientSession clientSession, Bson filter, Class<TResult> resultClass)Parameters:
clientSession - Client session for transaction supportfilter - Query filter (using Filters helper)resultClass - Class to deserialize results intoUsage Examples:
// Find all documents
FindIterable<Document> allDocs = collection.find();
for (Document doc : allDocs) {
System.out.println(doc.toJson());
}
// Find with filter
FindIterable<Document> adults = collection.find(Filters.gte("age", 18));
// Find with complex filter
Bson complexFilter = Filters.and(
Filters.gte("age", 25),
Filters.lt("age", 65),
Filters.eq("status", "active")
);
FindIterable<Document> results = collection.find(complexFilter);
// Find with sorting and projection
FindIterable<Document> sortedResults = collection.find()
.sort(Sorts.descending("age"))
.projection(Projections.include("name", "age"))
.limit(10)
.skip(5);
// Find with session
try (ClientSession session = mongoClient.startSession()) {
FindIterable<Document> sessionResults = collection.find(session, filter);
}
// Find into custom class
public class User {
private String name;
private int age;
// getters and setters
}
FindIterable<User> users = collection.find(filter, User.class);Retrieves a single document from the collection.
// Find first matching document
Document firstDoc = collection.find(Filters.eq("status", "active")).first();
// Find one with session
Document sessionDoc = collection.find(session, filter).first();Updates a single document in the collection.
UpdateResult updateOne(Bson filter, Bson update)
UpdateResult updateOne(Bson filter, Bson update, UpdateOptions options)
UpdateResult updateOne(ClientSession clientSession, Bson filter, Bson update)
UpdateResult updateOne(ClientSession clientSession, Bson filter, Bson update, UpdateOptions options)
UpdateResult updateOne(Bson filter, List<? extends Bson> update)
UpdateResult updateOne(Bson filter, List<? extends Bson> update, UpdateOptions options)
UpdateResult updateOne(ClientSession clientSession, Bson filter, List<? extends Bson> update)
UpdateResult updateOne(ClientSession clientSession, Bson filter, List<? extends Bson> update, UpdateOptions options)Parameters:
clientSession - Client session for transaction supportfilter - Query filter to match documentsupdate - Update operations or aggregation pipelineoptions - Update options (upsert, bypass validation, etc.)Usage Examples:
// Basic update
Bson filter = Filters.eq("_id", objectId);
Bson update = Updates.set("status", "updated");
UpdateResult result = collection.updateOne(filter, update);
System.out.println("Modified count: " + result.getModifiedCount());
// Update with multiple operations
Bson multiUpdate = Updates.combine(
Updates.set("status", "active"),
Updates.inc("loginCount", 1),
Updates.currentDate("lastLogin")
);
collection.updateOne(filter, multiUpdate);
// Upsert operation
UpdateOptions options = new UpdateOptions().upsert(true);
collection.updateOne(filter, update, options);
// Update with aggregation pipeline
List<Bson> pipeline = Arrays.asList(
Aggregates.addFields(new Field("totalScore",
new Document("$add", Arrays.asList("$score1", "$score2"))))
);
collection.updateOne(filter, pipeline);
// Update with session
try (ClientSession session = mongoClient.startSession()) {
collection.updateOne(session, filter, update);
}Updates multiple documents in the collection.
UpdateResult updateMany(Bson filter, Bson update)
UpdateResult updateMany(Bson filter, Bson update, UpdateOptions options)
UpdateResult updateMany(ClientSession clientSession, Bson filter, Bson update)
UpdateResult updateMany(ClientSession clientSession, Bson filter, Bson update, UpdateOptions options)
UpdateResult updateMany(Bson filter, List<? extends Bson> update)
UpdateResult updateMany(Bson filter, List<? extends Bson> update, UpdateOptions options)
UpdateResult updateMany(ClientSession clientSession, Bson filter, List<? extends Bson> update)
UpdateResult updateMany(ClientSession clientSession, Bson filter, List<? extends Bson> update, UpdateOptions options)Usage Examples:
// Update multiple documents
Bson filter = Filters.lt("lastLogin", LocalDateTime.now().minusDays(30));
Bson update = Updates.set("status", "inactive");
UpdateResult result = collection.updateMany(filter, update);
System.out.println("Modified " + result.getModifiedCount() + " documents");
// Bulk status update
Bson bulkUpdate = Updates.combine(
Updates.set("status", "archived"),
Updates.currentDate("archivedAt")
);
collection.updateMany(Filters.eq("category", "old"), bulkUpdate);Replaces a single document in the collection.
UpdateResult replaceOne(Bson filter, TDocument replacement)
UpdateResult replaceOne(Bson filter, TDocument replacement, ReplaceOptions options)
UpdateResult replaceOne(ClientSession clientSession, Bson filter, TDocument replacement)
UpdateResult replaceOne(ClientSession clientSession, Bson filter, TDocument replacement, ReplaceOptions options)Parameters:
clientSession - Client session for transaction supportfilter - Query filter to match documentreplacement - Complete replacement documentoptions - Replace options (upsert, bypass validation)Usage Examples:
// Replace entire document
Document replacement = new Document("name", "Updated Name")
.append("email", "updated@example.com")
.append("status", "active");
Bson filter = Filters.eq("_id", objectId);
UpdateResult result = collection.replaceOne(filter, replacement);
// Replace with upsert
ReplaceOptions options = new ReplaceOptions().upsert(true);
collection.replaceOne(filter, replacement, options);Deletes a single document from the collection.
DeleteResult deleteOne(Bson filter)
DeleteResult deleteOne(Bson filter, DeleteOptions options)
DeleteResult deleteOne(ClientSession clientSession, Bson filter)
DeleteResult deleteOne(ClientSession clientSession, Bson filter, DeleteOptions options)Parameters:
clientSession - Client session for transaction supportfilter - Query filter to match documentoptions - Delete options (collation, hint)Usage Examples:
// Delete single document
Bson filter = Filters.eq("_id", objectId);
DeleteResult result = collection.deleteOne(filter);
System.out.println("Deleted count: " + result.getDeletedCount());
// Delete with collation
DeleteOptions options = new DeleteOptions()
.collation(Collation.builder().locale("en").build());
collection.deleteOne(filter, options);
// Delete with session
try (ClientSession session = mongoClient.startSession()) {
collection.deleteOne(session, filter);
}Deletes multiple documents from the collection.
DeleteResult deleteMany(Bson filter)
DeleteResult deleteMany(Bson filter, DeleteOptions options)
DeleteResult deleteMany(ClientSession clientSession, Bson filter)
DeleteResult deleteMany(ClientSession clientSession, Bson filter, DeleteOptions options)Usage Examples:
// Delete multiple documents
Bson filter = Filters.lt("lastLogin", LocalDateTime.now().minusYears(1));
DeleteResult result = collection.deleteMany(filter);
System.out.println("Deleted " + result.getDeletedCount() + " inactive users");
// Delete all documents matching criteria
collection.deleteMany(Filters.eq("status", "expired"));Finds a single document and deletes it, returning the original document.
TDocument findOneAndDelete(Bson filter)
TDocument findOneAndDelete(Bson filter, FindOneAndDeleteOptions options)
TDocument findOneAndDelete(ClientSession clientSession, Bson filter)
TDocument findOneAndDelete(ClientSession clientSession, Bson filter, FindOneAndDeleteOptions options)Parameters:
clientSession - Client session for transaction supportfilter - Query filter to match documentoptions - Options (projection, sort, collation, hint)Usage Examples:
// Find and delete
Bson filter = Filters.eq("status", "pending");
Document deletedDoc = collection.findOneAndDelete(filter);
// Find and delete with sorting
FindOneAndDeleteOptions options = new FindOneAndDeleteOptions()
.sort(Sorts.ascending("priority"))
.projection(Projections.include("name", "priority"));
Document result = collection.findOneAndDelete(filter, options);Finds a single document and updates it, returning either the original or updated document.
TDocument findOneAndUpdate(Bson filter, Bson update)
TDocument findOneAndUpdate(Bson filter, Bson update, FindOneAndUpdateOptions options)
TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, Bson update)
TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, Bson update, FindOneAndUpdateOptions options)
TDocument findOneAndUpdate(Bson filter, List<? extends Bson> update)
TDocument findOneAndUpdate(Bson filter, List<? extends Bson> update, FindOneAndUpdateOptions options)
TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, List<? extends Bson> update)
TDocument findOneAndUpdate(ClientSession clientSession, Bson filter, List<? extends Bson> update, FindOneAndUpdateOptions options)Usage Examples:
// Find and update, return updated document
Bson filter = Filters.eq("status", "pending");
Bson update = Updates.combine(
Updates.set("status", "processing"),
Updates.currentDate("startedAt")
);
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions()
.returnDocument(ReturnDocument.AFTER)
.upsert(true);
Document updatedDoc = collection.findOneAndUpdate(filter, update, options);Finds a single document and replaces it, returning either the original or replacement document.
TDocument findOneAndReplace(Bson filter, TDocument replacement)
TDocument findOneAndReplace(Bson filter, TDocument replacement, FindOneAndReplaceOptions options)
TDocument findOneAndReplace(ClientSession clientSession, Bson filter, TDocument replacement)
TDocument findOneAndReplace(ClientSession clientSession, Bson filter, TDocument replacement, FindOneAndReplaceOptions options)Usage Examples:
// Find and replace
Document replacement = new Document("name", "New Name")
.append("status", "replaced");
FindOneAndReplaceOptions options = new FindOneAndReplaceOptions()
.returnDocument(ReturnDocument.AFTER);
Document result = collection.findOneAndReplace(filter, replacement, options);Returns the count of documents that match the filter.
long countDocuments()
long countDocuments(Bson filter)
long countDocuments(CountOptions options)
long countDocuments(Bson filter, CountOptions options)
long countDocuments(ClientSession clientSession)
long countDocuments(ClientSession clientSession, Bson filter)
long countDocuments(ClientSession clientSession, CountOptions options)
long countDocuments(ClientSession clientSession, Bson filter, CountOptions options)Parameters:
clientSession - Client session for transaction supportfilter - Query filter (optional)options - Count options (limit, skip, hint, collation)Usage Examples:
// Count all documents
long totalCount = collection.countDocuments();
// Count with filter
long activeUsers = collection.countDocuments(Filters.eq("status", "active"));
// Count with options
CountOptions options = new CountOptions()
.limit(1000)
.maxTime(5, TimeUnit.SECONDS);
long count = collection.countDocuments(filter, options);Returns an estimate of the count of documents in the collection using collection metadata.
long estimatedDocumentCount()
long estimatedDocumentCount(EstimatedDocumentCountOptions options)Usage Examples:
// Fast estimate count
long estimatedCount = collection.estimatedDocumentCount();
// Estimate with timeout
EstimatedDocumentCountOptions options = new EstimatedDocumentCountOptions()
.maxTime(3, TimeUnit.SECONDS);
long count = collection.estimatedDocumentCount(options);Executes a mix of inserts, updates, and deletes in a single batch.
BulkWriteResult bulkWrite(List<? extends WriteModel<? extends TDocument>> requests)
BulkWriteResult bulkWrite(List<? extends WriteModel<? extends TDocument>> requests, BulkWriteOptions options)
BulkWriteResult bulkWrite(ClientSession clientSession, List<? extends WriteModel<? extends TDocument>> requests)
BulkWriteResult bulkWrite(ClientSession clientSession, List<? extends WriteModel<? extends TDocument>> requests, BulkWriteOptions options)Parameters:
clientSession - Client session for transaction supportrequests - List of write operationsoptions - Bulk write options (ordered, bypass validation)Usage Examples:
// Mixed bulk operations
List<WriteModel<Document>> bulkOps = Arrays.asList(
new InsertOneModel<>(new Document("name", "New User")),
new UpdateOneModel<>(
Filters.eq("_id", objectId1),
Updates.set("status", "updated")
),
new DeleteOneModel<>(Filters.eq("_id", objectId2)),
new ReplaceOneModel<>(
Filters.eq("_id", objectId3),
new Document("name", "Replaced").append("status", "new")
)
);
BulkWriteResult result = collection.bulkWrite(bulkOps);
System.out.println("Inserted: " + result.getInsertedCount());
System.out.println("Modified: " + result.getModifiedCount());
System.out.println("Deleted: " + result.getDeletedCount());
// Unordered bulk write
BulkWriteOptions options = new BulkWriteOptions().ordered(false);
collection.bulkWrite(bulkOps, options);Returns a new MongoCollection instance with a different codec registry.
<NewTDocument> MongoCollection<NewTDocument> withCodecRegistry(CodecRegistry codecRegistry)Usage Examples:
// Custom codec registry
CodecRegistry customRegistry = CodecRegistries.fromRegistries(
CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.JAVA_LEGACY)),
MongoClientSettings.getDefaultCodecRegistry()
);
MongoCollection<Document> customCollection = collection.withCodecRegistry(customRegistry);Returns a new MongoCollection instance with a different read preference.
MongoCollection<TDocument> withReadPreference(ReadPreference readPreference)Usage Examples:
// Read from secondary
MongoCollection<Document> secondaryCollection = collection
.withReadPreference(ReadPreference.secondary());
// Read from nearest with max staleness
MongoCollection<Document> nearestCollection = collection
.withReadPreference(ReadPreference.nearest(15, TimeUnit.SECONDS));Returns a new MongoCollection instance with a different write concern.
MongoCollection<TDocument> withWriteConcern(WriteConcern writeConcern)Usage Examples:
// Majority write concern
MongoCollection<Document> safeCollection = collection
.withWriteConcern(WriteConcern.MAJORITY);
// Custom write concern
WriteConcern customConcern = WriteConcern.W2.withJournal(true);
MongoCollection<Document> customCollection = collection
.withWriteConcern(customConcern);Returns a new MongoCollection instance with a different read concern.
MongoCollection<TDocument> withReadConcern(ReadConcern readConcern)Usage Examples:
// Linearizable read concern
MongoCollection<Document> linearCollection = collection
.withReadConcern(ReadConcern.LINEARIZABLE);
// Majority read concern
MongoCollection<Document> majorityCollection = collection
.withReadConcern(ReadConcern.MAJORITY);All CRUD operations support MongoDB transactions when used with a ClientSession:
try (ClientSession session = mongoClient.startSession()) {
TransactionOptions txnOptions = TransactionOptions.builder()
.readPreference(ReadPreference.primary())
.readConcern(ReadConcern.LOCAL)
.writeConcern(WriteConcern.MAJORITY)
.build();
session.withTransaction(() -> {
collection.insertOne(session, document1);
collection.updateOne(session, filter, update);
collection.deleteOne(session, deleteFilter);
return "Transaction completed";
}, txnOptions);
}try {
InsertOneResult result = collection.insertOne(document);
} catch (MongoWriteException e) {
if (e.getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
System.out.println("Document already exists");
}
} catch (MongoException e) {
System.out.println("Database error: " + e.getMessage());
}// Use projection to limit returned fields
FindIterable<Document> results = collection.find(filter)
.projection(Projections.include("name", "status"))
.batchSize(1000);
// Use hint for index selection
collection.find(filter)
.hint(new Document("status", 1));
// Use allowDiskUse for large operations
collection.find(filter)
.allowDiskUse(true);This comprehensive guide covers all the major CRUD operations available in the MongoDB Java driver's MongoCollection interface, including advanced features like transactions, bulk operations, and configuration options.
Install with Tessl CLI
npx tessl i tessl/maven-org-mongodb--mongodb-driver-sync