clientBulkWriteOperation(
@@ -866,4 +873,14 @@ private SearchIndexRequest createSearchIndexRequest(final SearchIndexModel model
return new SearchIndexRequest(definition, indexName, searchIndexType);
}
+
+ /**
+ * Encodes {@code overridingCommandOptions} in a way that does not require {@link #codecRegistry} to have a {@link Codec}
+ * for {@link Document}, if {@code overridingCommandOptions} is {@linkplain Document#isEmpty() empty}.
+ */
+ private BsonDocument encodeOverridingCommandOptions(final Document overridingCommandOptions) {
+ return overridingCommandOptions.isEmpty()
+ ? new BsonDocument()
+ : overridingCommandOptions.toBsonDocument(BsonDocument.class, codecRegistry);
+ }
}
diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateOperationSpecification.groovy
index 9e8d6a8277e..192e7dcbfb9 100644
--- a/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateOperationSpecification.groovy
+++ b/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateOperationSpecification.groovy
@@ -146,12 +146,15 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification {
.allowDiskUse(true)
.batchSize(10)
.collation(defaultCollation)
+ .overridingCommandOptions(new BsonDocument('let', new BsonDocument('overriding', new BsonInt32(2))))
+ .let(new BsonDocument('overridden', new BsonInt32(1)))
expectedCommand = new BsonDocument('aggregate', new BsonString(helper.namespace.getCollectionName()))
.append('pipeline', new BsonArray(pipeline))
.append('allowDiskUse', new BsonBoolean(true))
.append('collation', defaultCollation.asDocument())
.append('cursor', new BsonDocument('batchSize', new BsonInt32(10)))
+ .append('let', new BsonDocument('overriding', new BsonInt32(2)))
then:
testOperation(operation, [3, 4, 0], expectedCommand, async, helper.cursorResult)
diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy
index a14c4323fdd..367563d484e 100644
--- a/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy
+++ b/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy
@@ -243,15 +243,26 @@ class AggregateToCollectionOperationSpecification extends OperationFunctionalSpe
operation.hint(new BsonString('x_1'))
expectedCommand.append('hint', new BsonString('x_1'))
}
+ if (useOverridingCommandOptions) {
+ operation.overridingCommandOptions(new BsonDocument('let', new BsonDocument('overriding', new BsonInt32(2))))
+ .let(new BsonDocument('overridden', new BsonInt32(1)))
+ expectedCommand.append('let', new BsonDocument('overriding', new BsonInt32(2)))
+ }
then:
testOperation(operation, serverVersion, expectedCommand, async, BsonDocument.parse('{ok: 1}'),
true, false, ReadPreference.primary(), false)
where:
- serverVersion | includeBypassValidation | includeReadConcern | includeWriteConcern | includeCollation | async | useCursor | useHint
- [3, 6, 0] | true | true | true | true | true | true | true
- [3, 6, 0] | true | true | true | true | false | true | false
+ serverVersion << [[3, 6, 0], [3, 6, 0]]
+ includeBypassValidation << [true, true]
+ includeReadConcern << [true, true]
+ includeWriteConcern << [true, true]
+ includeCollation << [true, true]
+ async << [true, false]
+ useCursor << [true, true]
+ useHint << [true, false]
+ useOverridingCommandOptions << [true, true]
}
def 'should support collation'() {
diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationProseTestSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationProseTestSpecification.groovy
index c7d3314b5b7..0a62db77821 100644
--- a/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationProseTestSpecification.groovy
+++ b/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationProseTestSpecification.groovy
@@ -40,7 +40,11 @@ import static com.mongodb.ClusterFixture.isStandalone
import static com.mongodb.internal.connection.ServerHelper.waitForLastRelease
import static java.util.Arrays.asList
-// See https://github.com/mongodb/specifications/tree/master/source/change-streams/tests/README.md#prose-tests
+/**
+ * See Prose Tests.
+ *
+ * New tests should be added to {@link com.mongodb.client.ChangeStreamProseTest}.
+ */
@IgnoreIf({ isStandalone() })
class ChangeStreamOperationProseTestSpecification extends OperationFunctionalSpecification {
diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationSpecification.groovy
index fc2431f03f3..91756655d15 100644
--- a/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationSpecification.groovy
+++ b/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationSpecification.groovy
@@ -21,6 +21,7 @@ import com.mongodb.MongoNamespace
import com.mongodb.OperationFunctionalSpecification
import com.mongodb.ReadConcern
import com.mongodb.WriteConcern
+import com.mongodb.client.model.Collation
import com.mongodb.client.model.CreateCollectionOptions
import com.mongodb.client.model.changestream.ChangeStreamDocument
import com.mongodb.client.model.changestream.FullDocument
@@ -114,7 +115,8 @@ class ChangeStreamOperationSpecification extends OperationFunctionalSpecificatio
def operation = new ChangeStreamOperation(namespace, FullDocument.DEFAULT,
FullDocumentBeforeChange.DEFAULT, pipeline, new DocumentCodec(), changeStreamLevel as ChangeStreamLevel, null)
.batchSize(5)
- .collation(defaultCollation)
+ .overridingCommandOptions(new BsonDocument('collation', defaultCollation.asDocument()))
+ .collation(Collation.builder().locale('overridden').build())
.startAtOperationTime(new BsonTimestamp())
def expectedCommand = new BsonDocument('aggregate', aggregate)
diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt
index 439a0ccbb29..d5272b6ef9b 100644
--- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt
+++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt
@@ -74,4 +74,8 @@ data class SyncAggregateIterable(val wrapped: AggregateFlow) :
override fun explain(explainResultClass: Class, verbosity: ExplainVerbosity): E = runBlocking {
wrapped.explain(explainResultClass, verbosity)
}
+
+ override fun commandOption(name: String, value: Any): SyncAggregateIterable = apply {
+ wrapped.commandOption(name, value)
+ }
}
diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt
index 3f5269cd10d..b2892f642ef 100644
--- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt
+++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt
@@ -60,4 +60,8 @@ data class SyncChangeStreamIterable(val wrapped: ChangeStreamFlow) :
override fun startAtOperationTime(startAtOperationTime: BsonTimestamp): SyncChangeStreamIterable = apply {
wrapped.startAtOperationTime(startAtOperationTime)
}
+
+ override fun commandOption(name: String, value: Any): SyncChangeStreamIterable = apply {
+ wrapped.commandOption(name, value)
+ }
}
diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt
index a1debfd812f..d69caa011a7 100644
--- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt
+++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt
@@ -29,6 +29,7 @@ import kotlinx.coroutines.reactive.awaitFirstOrNull
import kotlinx.coroutines.reactive.awaitSingle
import org.bson.BsonValue
import org.bson.Document
+import org.bson.codecs.configuration.CodecRegistry
import org.bson.conversions.Bson
/**
@@ -216,6 +217,22 @@ public class AggregateFlow(private val wrapped: AggregatePublisher)
public suspend inline fun explain(verbosity: ExplainVerbosity? = null): R =
explain(R::class.java, verbosity)
+ /**
+ * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies
+ * your needs. The behavior of this method is undefined if it is used to set any of the following:
+ * - a field from the following set: [maxTimeMS][maxTime], `cursor`, [explain][explain], [comment][comment],
+ * [collation][collation];
+ * - a field that is configurable via means other than [AggregateFlow] methods;
+ * - a field that is also set via a different [AggregateFlow] method.
+ *
+ * @param name The name of the optional command field.
+ * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which
+ * must have a codec for [Document] regardless of the type of `value`.
+ * @return `this`.
+ * @since 5.17
+ */
+ public fun commandOption(name: String, value: Any): AggregateFlow = apply { wrapped.commandOption(name, value) }
+
/**
* Requests [AggregateFlow] to start streaming data according to the specified aggregation pipeline.
* - If the aggregation pipeline ends with an `$out` or `$merge` stage, then finds all documents in the affected
diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt
index 55bfeb82060..3982f888d0a 100644
--- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt
+++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt
@@ -27,6 +27,8 @@ import kotlinx.coroutines.reactive.asFlow
import org.bson.BsonDocument
import org.bson.BsonTimestamp
import org.bson.BsonValue
+import org.bson.Document
+import org.bson.codecs.configuration.CodecRegistry
/**
* Flow implementation for change streams.
@@ -173,6 +175,24 @@ public class ChangeStreamFlow(private val wrapped: ChangeStreamPublishe
public fun showExpandedEvents(showExpandedEvents: Boolean): ChangeStreamFlow = apply {
wrapped.showExpandedEvents(showExpandedEvents)
}
+
+ /**
+ * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies
+ * your needs. The behavior of this method is undefined if it is used to set any of the following:
+ * - a field from the following set: `maxTimeMS`, `cursor`, `explain`, [comment][comment];
+ * - a field that is configurable via means other than [ChangeStreamFlow] methods;
+ * - a field that is also set via a different [ChangeStreamFlow] method.
+ *
+ * @param name The name of the optional command field.
+ * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which
+ * must have a codec for [Document] regardless of the type of `value`.
+ * @return `this`.
+ * @since 5.17
+ */
+ public fun commandOption(name: String, value: Any): ChangeStreamFlow = apply {
+ wrapped.commandOption(name, value)
+ }
+
public override suspend fun collect(collector: FlowCollector>): Unit =
wrapped.asFlow().collect(collector)
}
diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt
index ab4b9694986..ca88c358bf9 100644
--- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt
+++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt
@@ -59,6 +59,10 @@ class AggregateFlowTest {
val hint = Document("h", 1)
val hintString = "hintString"
val verbosity = ExplainVerbosity.QUERY_PLANNER
+ val stringCommandOptionName = "stringCommandOptionName"
+ val stringCommandOptionValue = "stringCommandOptionValue"
+ val intCommandOptionName = "intCommandOptionName"
+ val intCommandOptionValue = 1
flow.allowDiskUse(true)
flow.batchSize(batchSize)
@@ -74,6 +78,8 @@ class AggregateFlowTest {
flow.maxTime(1)
flow.maxTime(1, TimeUnit.SECONDS)
flow.timeoutMode(TimeoutMode.ITERATION)
+ flow.commandOption(stringCommandOptionName, stringCommandOptionValue)
+ flow.commandOption(intCommandOptionName, intCommandOptionValue)
verify(wrapped).allowDiskUse(true)
verify(wrapped).batchSize(batchSize)
@@ -89,6 +95,8 @@ class AggregateFlowTest {
verify(wrapped).maxTime(1, TimeUnit.SECONDS)
verify(wrapped).let(bson)
verify(wrapped).timeoutMode(TimeoutMode.ITERATION)
+ verify(wrapped).commandOption(stringCommandOptionName, stringCommandOptionValue)
+ verify(wrapped).commandOption(intCommandOptionName, intCommandOptionValue)
whenever(wrapped.explain(Document::class.java)).doReturn(Mono.fromCallable { Document() })
whenever(wrapped.explain(Document::class.java, verbosity)).doReturn(Mono.fromCallable { Document() })
diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlowTest.kt
index 47030468588..6a4a980a29c 100644
--- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlowTest.kt
+++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlowTest.kt
@@ -56,6 +56,10 @@ class ChangeStreamFlowTest {
val comment = "comment"
val operationTime = BsonTimestamp(1)
val resumeToken = BsonDocument()
+ val stringCommandOptionName = "stringCommandOptionName"
+ val stringCommandOptionValue = "stringCommandOptionValue"
+ val intCommandOptionName = "intCommandOptionName"
+ val intCommandOptionValue = 1
flow.batchSize(batchSize)
flow.collation(collation)
@@ -69,6 +73,8 @@ class ChangeStreamFlowTest {
flow.showExpandedEvents(true)
flow.startAfter(resumeToken)
flow.startAtOperationTime(operationTime)
+ flow.commandOption(stringCommandOptionName, stringCommandOptionValue)
+ flow.commandOption(intCommandOptionName, intCommandOptionValue)
verify(wrapped).batchSize(batchSize)
verify(wrapped).collation(collation)
@@ -82,6 +88,8 @@ class ChangeStreamFlowTest {
verify(wrapped).showExpandedEvents(true)
verify(wrapped).startAfter(resumeToken)
verify(wrapped).startAtOperationTime(operationTime)
+ verify(wrapped).commandOption(stringCommandOptionName, stringCommandOptionValue)
+ verify(wrapped).commandOption(intCommandOptionName, intCommandOptionValue)
whenever(wrapped.withDocumentClass(BsonDocument::class.java)).doReturn(mock())
runBlocking { flow.withDocumentClass() }
diff --git a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt
index f0fd6d7a1a4..778f000ecf9 100644
--- a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt
+++ b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt
@@ -233,7 +233,6 @@ class AggregatesTest {
}
@Test
- @Suppress("LongMethod")
fun accumulators() {
assertEquals(com.mongodb.client.model.Accumulators.sum("age", 1), sum(Person::age, 1))
diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt
index b563c67c368..6c7bb2a212e 100644
--- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt
+++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt
@@ -70,4 +70,8 @@ internal class SyncAggregateIterable(val wrapped: AggregateIterable)
override fun explain(explainResultClass: Class, verbosity: ExplainVerbosity): E =
wrapped.explain(explainResultClass, verbosity)
+
+ override fun commandOption(name: String, value: Any): SyncAggregateIterable = apply {
+ wrapped.commandOption(name, value)
+ }
}
diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt
index 0d579e68006..8cb39b0bd79 100644
--- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt
+++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt
@@ -58,4 +58,8 @@ internal class SyncChangeStreamIterable(val wrapped: ChangeStreamIterab
override fun startAtOperationTime(startAtOperationTime: BsonTimestamp): SyncChangeStreamIterable = apply {
wrapped.startAtOperationTime(startAtOperationTime)
}
+
+ override fun commandOption(name: String, value: Any): SyncChangeStreamIterable = apply {
+ wrapped.commandOption(name, value)
+ }
}
diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt
index 49130b82c60..2ef638c0360 100644
--- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt
+++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt
@@ -24,6 +24,7 @@ import com.mongodb.client.model.Collation
import java.util.concurrent.TimeUnit
import org.bson.BsonValue
import org.bson.Document
+import org.bson.codecs.configuration.CodecRegistry
import org.bson.conversions.Bson
/**
@@ -219,4 +220,22 @@ public class AggregateIterable(private val wrapped: JAggregateIterable<
*/
public inline fun explain(verbosity: ExplainVerbosity? = null): R =
explain(R::class.java, verbosity)
+
+ /**
+ * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies
+ * your needs. The behavior of this method is undefined if it is used to set any of the following:
+ * - a field from the following set: [maxTimeMS][maxTime], `cursor`, [explain][explain], [comment][comment],
+ * [collation][collation];
+ * - a field that is configurable via means other than [AggregateIterable] methods;
+ * - a field that is also set via a different [AggregateIterable] method.
+ *
+ * @param name The name of the optional command field.
+ * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which
+ * must have a codec for [Document] regardless of the type of `value`.
+ * @return `this`.
+ * @since 5.17
+ */
+ public fun commandOption(name: String, value: Any): AggregateIterable = apply {
+ wrapped.commandOption(name, value)
+ }
}
diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt
index cf7cc35b0b0..b5540c7cf17 100644
--- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt
+++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt
@@ -24,6 +24,8 @@ import java.util.concurrent.TimeUnit
import org.bson.BsonDocument
import org.bson.BsonTimestamp
import org.bson.BsonValue
+import org.bson.Document
+import org.bson.codecs.configuration.CodecRegistry
/**
* Iterable like implementation for change streams.
@@ -178,4 +180,21 @@ public class ChangeStreamIterable(private val wrapped: JChangeStreamIte
public fun showExpandedEvents(showExpandedEvents: Boolean): ChangeStreamIterable = apply {
wrapped.showExpandedEvents(showExpandedEvents)
}
+
+ /**
+ * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies
+ * your needs. The behavior of this method is undefined if it is used to set any of the following:
+ * - a field from the following set: `maxTimeMS`, `cursor`, `explain`, [comment][comment];
+ * - a field that is configurable via means other than [ChangeStreamIterable] methods;
+ * - a field that is also set via a different [ChangeStreamIterable] method.
+ *
+ * @param name The name of the optional command field.
+ * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which
+ * must have a codec for [Document] regardless of the type of `value`.
+ * @return `this`.
+ * @since 5.17
+ */
+ public fun commandOption(name: String, value: Any): ChangeStreamIterable = apply {
+ wrapped.commandOption(name, value)
+ }
}
diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt
index 83ca9bce0ad..9adba2627ed 100644
--- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt
+++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt
@@ -57,6 +57,10 @@ class AggregateIterableTest {
val hint = Document("h", 1)
val hintString = "hintString"
val verbosity = ExplainVerbosity.QUERY_PLANNER
+ val stringCommandOptionName = "stringCommandOptionName"
+ val stringCommandOptionValue = "stringCommandOptionValue"
+ val intCommandOptionName = "intCommandOptionName"
+ val intCommandOptionValue = 1
whenever(wrapped.explain(Document::class.java)).doReturn(mock())
whenever(wrapped.explain(Document::class.java, verbosity)).doReturn(mock())
@@ -82,6 +86,8 @@ class AggregateIterableTest {
iterable.maxTime(1)
iterable.maxTime(1, TimeUnit.SECONDS)
iterable.timeoutMode(TimeoutMode.ITERATION)
+ iterable.commandOption(stringCommandOptionName, stringCommandOptionValue)
+ iterable.commandOption(intCommandOptionName, intCommandOptionValue)
verify(wrapped).allowDiskUse(true)
verify(wrapped).batchSize(batchSize)
@@ -100,6 +106,8 @@ class AggregateIterableTest {
verify(wrapped).maxTime(1, TimeUnit.SECONDS)
verify(wrapped).let(bson)
verify(wrapped).timeoutMode(TimeoutMode.ITERATION)
+ verify(wrapped).commandOption(stringCommandOptionName, stringCommandOptionValue)
+ verify(wrapped).commandOption(intCommandOptionName, intCommandOptionValue)
iterable.toCollection()
verify(wrapped).toCollection()
diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ChangeStreamIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ChangeStreamIterableTest.kt
index 53d56485c21..d7781b3a02d 100644
--- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ChangeStreamIterableTest.kt
+++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ChangeStreamIterableTest.kt
@@ -54,6 +54,10 @@ class ChangeStreamIterableTest {
val comment = "comment"
val operationTime = BsonTimestamp(1)
val resumeToken = BsonDocument()
+ val stringCommandOptionName = "stringCommandOptionName"
+ val stringCommandOptionValue = "stringCommandOptionValue"
+ val intCommandOptionName = "intCommandOptionName"
+ val intCommandOptionValue = 1
whenever(wrapped.withDocumentClass(BsonDocument::class.java)).doReturn(mock())
whenever(wrapped.cursor()).doReturn(mock())
@@ -72,6 +76,8 @@ class ChangeStreamIterableTest {
iterable.startAfter(resumeToken)
iterable.startAtOperationTime(operationTime)
iterable.withDocumentClass()
+ iterable.commandOption(stringCommandOptionName, stringCommandOptionValue)
+ iterable.commandOption(intCommandOptionName, intCommandOptionValue)
verify(wrapped).batchSize(batchSize)
verify(wrapped).collation(collation)
@@ -87,6 +93,8 @@ class ChangeStreamIterableTest {
verify(wrapped).startAfter(resumeToken)
verify(wrapped).startAtOperationTime(operationTime)
verify(wrapped).withDocumentClass(BsonDocument::class.java)
+ verify(wrapped).commandOption(stringCommandOptionName, stringCommandOptionValue)
+ verify(wrapped).commandOption(intCommandOptionName, intCommandOptionValue)
verifyNoMoreInteractions(wrapped)
}
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java
index 4f18fe272bc..de71389e878 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java
@@ -27,6 +27,7 @@
import com.mongodb.lang.Nullable;
import org.bson.BsonValue;
import org.bson.Document;
+import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
@@ -272,4 +273,27 @@ public interface AggregatePublisher extends Publisher {
* @mongodb.server.release 3.6
*/
Publisher explain(Class explainResultClass, ExplainVerbosity verbosity);
+
+ /**
+ * Sets an optional field of the {@code aggregate} command in situations when there is no method that better satisfies your needs.
+ * The behavior of this method is undefined if it is used to set any of the following:
+ *
+ * -
+ * a field from the following set:
+ * {@link #maxTime(long, TimeUnit) maxTimeMS}, {@code cursor}, {@link #explain(Class, ExplainVerbosity) explain},
+ * {@link #comment(BsonValue) comment}, {@link #collation(Collation) collation};
+ * -
+ * a field that is configurable via means other than {@link AggregatePublisher} methods;
+ * -
+ * a field that is also set via a different {@link AggregatePublisher} method.
+ *
+ *
+ * @param name The name of the optional command field.
+ * @param value The value of the field specified by {@code name}.
+ * It is encoded via the configured {@link CodecRegistry},
+ * which must have a codec for {@link Document} regardless of the type of {@code value}.
+ * @return {@code this}.
+ * @since 5.17
+ */
+ AggregatePublisher commandOption(String name, Object value);
}
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java
index 27dc7b58238..440449c6747 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java
@@ -25,6 +25,8 @@
import org.bson.BsonDocument;
import org.bson.BsonTimestamp;
import org.bson.BsonValue;
+import org.bson.Document;
+import org.bson.codecs.configuration.CodecRegistry;
import org.reactivestreams.Publisher;
import java.util.concurrent.TimeUnit;
@@ -178,4 +180,27 @@ public interface ChangeStreamPublisher extends Publisher showExpandedEvents(boolean showExpandedEvents);
+
+ /**
+ * Sets an optional field of the {@code aggregate} command in situations when there is no method that better satisfies your needs.
+ * The behavior of this method is undefined if it is used to set any of the following:
+ *
+ * -
+ * a field from the following set:
+ * {@code maxTimeMS}, {@code cursor}, {@code explain},
+ * {@link #comment(BsonValue) comment};
+ * -
+ * a field that is configurable via means other than {@link ChangeStreamPublisher} methods;
+ * -
+ * a field that is also set via a different {@link ChangeStreamPublisher} method.
+ *
+ *
+ * @param name The name of the optional command field.
+ * @param value The value of the field specified by {@code name}.
+ * It is encoded via the configured {@link CodecRegistry},
+ * which must have a codec for {@link Document} regardless of the type of {@code value}.
+ * @return {@code this}.
+ * @since 5.17
+ */
+ ChangeStreamPublisher commandOption(String name, Object value);
}
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionNamesPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionNamesPublisher.java
index a28fcff1030..157ea8f3542 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionNamesPublisher.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionNamesPublisher.java
@@ -29,6 +29,10 @@
* @since 5.0
* @mongodb.driver.manual reference/command/listCollections/ listCollections
*/
+/*
+ * This interface should declare almost the same set of methods as `ListCollectionsPublisher`.
+ * See `com.mongodb.reactivestreams.client.ListCollectionNamesPublisherTest`.
+ */
public interface ListCollectionNamesPublisher extends Publisher {
/**
* Sets the query filter to apply to the query.
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java
index 50808928172..d5e391d4f25 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java
@@ -33,6 +33,10 @@
* @since 1.0
* @mongodb.driver.manual reference/command/listCollections/ listCollections
*/
+/*
+ * This interface should declare almost the same set of methods as `ListCollectionNamesPublisher`.
+ * See `com.mongodb.reactivestreams.client.ListCollectionNamesPublisherTest`.
+ */
public interface ListCollectionsPublisher extends Publisher {
/**
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java
index e37f536a4f7..30fca259d79 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java
@@ -41,9 +41,13 @@
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
+import static com.mongodb.assertions.Assertions.isTrueArgument;
import static com.mongodb.assertions.Assertions.notNull;
+import static com.mongodb.internal.operation.AggregateOperation.FORBIDDEN_COMMAND_OPTION_NAME;
+import static java.lang.String.format;
-final class AggregatePublisherImpl extends BatchCursorPublisher implements AggregatePublisher {
+final class AggregatePublisherImpl extends BatchCursorPublisher
+ implements InternalCommonBatchCursorPublisher, AggregatePublisher {
private final List extends Bson> pipeline;
private final AggregationLevel aggregationLevel;
private Boolean allowDiskUse;
@@ -170,6 +174,14 @@ public Publisher explain(final Class explainResultClass, final Explain
return publishExplain(explainResultClass, notNull("verbosity", verbosity));
}
+ @Override
+ public AggregatePublisher commandOption(final String name, final Object value) {
+ notNull("name", name);
+ isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTION_NAME.test(name));
+ overridingCommandOption(name, notNull("value", value));
+ return this;
+ }
+
private Publisher publishExplain(final Class explainResultClass, @Nullable final ExplainVerbosity verbosity) {
notNull("explainDocumentClass", explainResultClass);
return getMongoOperationPublisher().createReadOperationMono(
@@ -204,12 +216,14 @@ Function, TimeoutSettings> getTimeoutSettings() {
private ReadOperationExplainable asAggregateOperation(final int initialBatchSize) {
return getOperations()
.aggregate(pipeline, getDocumentClass(), getTimeoutMode(),
- initialBatchSize, collation, hint, hintString, comment, variables, allowDiskUse, aggregationLevel);
+ initialBatchSize, collation, hint, hintString, comment, variables, allowDiskUse, aggregationLevel,
+ getOverridingCommandOptions());
}
private ReadOperationSimple getAggregateToCollectionOperation() {
return getOperations().aggregateToCollection(pipeline, getTimeoutMode(), allowDiskUse, bypassDocumentValidation,
- collation, hint, hintString, comment, variables, aggregationLevel);
+ collation, hint, hintString, comment, variables, aggregationLevel,
+ getOverridingCommandOptions());
}
@Nullable
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java
index 1d68eb0e56a..b651433d450 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java
@@ -27,6 +27,7 @@
import com.mongodb.internal.operation.ReadOperationCursor;
import com.mongodb.lang.Nullable;
import com.mongodb.reactivestreams.client.ClientSession;
+import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
@@ -42,20 +43,19 @@
@VisibleForTesting(otherwise = VisibleForTesting.AccessModifier.PROTECTED)
public abstract class BatchCursorPublisher implements Publisher {
+ @Nullable
private final ClientSession clientSession;
private final MongoOperationPublisher mongoOperationPublisher;
+ @Nullable
private Integer batchSize;
+ @Nullable
private TimeoutMode timeoutMode;
+ private final Document overridingCommandOptions;
BatchCursorPublisher(@Nullable final ClientSession clientSession, final MongoOperationPublisher mongoOperationPublisher) {
- this(clientSession, mongoOperationPublisher, null);
- }
-
- BatchCursorPublisher(@Nullable final ClientSession clientSession, final MongoOperationPublisher mongoOperationPublisher,
- @Nullable final Integer batchSize) {
this.clientSession = clientSession;
this.mongoOperationPublisher = notNull("mongoOperationPublisher", mongoOperationPublisher);
- this.batchSize = batchSize;
+ overridingCommandOptions = new Document();
}
abstract ReadOperationCursor asReadOperation(int initialBatchSize);
@@ -90,10 +90,6 @@ CodecRegistry getCodecRegistry() {
return mongoOperationPublisher.getCodecRegistry();
}
- boolean getRetryReads() {
- return mongoOperationPublisher.getRetryReads();
- }
-
Class getDocumentClass() {
return mongoOperationPublisher.getDocumentClass();
}
@@ -137,6 +133,25 @@ public Publisher first() {
});
}
+ /**
+ * @see InternalCommonBatchCursorPublisher#commandOption(String, Object)
+ * @see #getOverridingCommandOptions()
+ */
+ Publisher overridingCommandOption(final String name, final Object value) {
+ overridingCommandOptions.put(name, value);
+ return this;
+ }
+
+ /**
+ * @see #overridingCommandOption(String, Object)
+ */
+ Document getOverridingCommandOptions() {
+ // An application may mutate `overridingCommandOptions` after subscribing to a `Publisher`.
+ // Such a mutation must not conflict with `overridingCommandOptions` being read while publishing.
+ // That is why we must return a shallow copy of `overridingCommandOptions`.
+ return new Document(overridingCommandOptions);
+ }
+
@Override
public void subscribe(final Subscriber super T> subscriber) {
new BatchCursorFlux<>(this).subscribe(subscriber);
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java
index b00dfb85952..7d7adc30e49 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java
@@ -31,6 +31,7 @@
import org.bson.BsonString;
import org.bson.BsonTimestamp;
import org.bson.BsonValue;
+import org.bson.Document;
import org.bson.codecs.Codec;
import org.bson.conversions.Bson;
import org.reactivestreams.Publisher;
@@ -39,11 +40,14 @@
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
+import static com.mongodb.assertions.Assertions.isTrueArgument;
import static com.mongodb.assertions.Assertions.notNull;
+import static com.mongodb.internal.operation.ChangeStreamOperation.FORBIDDEN_COMMAND_OPTION_NAME;
+import static java.lang.String.format;
final class ChangeStreamPublisherImpl extends BatchCursorPublisher>
- implements ChangeStreamPublisher {
+ implements InternalCommonBatchCursorPublisher>, ChangeStreamPublisher {
private final List extends Bson> pipeline;
private final Codec> codec;
@@ -134,11 +138,19 @@ public ChangeStreamPublisher collation(@Nullable final Collation collation) {
@Override
public Publisher withDocumentClass(final Class clazz) {
- return new BatchCursorPublisher(getClientSession(), getMongoOperationPublisher().withDocumentClass(clazz),
- getBatchSize()) {
+ return new BatchCursorPublisher(getClientSession(), getMongoOperationPublisher().withDocumentClass(clazz)) {
+ {
+ Integer batchSize = ChangeStreamPublisherImpl.this.getBatchSize();
+ if (batchSize != null) {
+ this.batchSize(batchSize);
+ }
+ ChangeStreamPublisherImpl.this.getOverridingCommandOptions().forEach(this::overridingCommandOption);
+ }
+
@Override
ReadOperationCursor asReadOperation(final int initialBatchSize) {
- return createChangeStreamOperation(getMongoOperationPublisher().getCodecRegistry().get(clazz), initialBatchSize);
+ return createChangeStreamOperation(
+ getMongoOperationPublisher().getCodecRegistry().get(clazz), initialBatchSize, getOverridingCommandOptions());
}
@Override
@@ -166,9 +178,17 @@ public ChangeStreamPublisherImpl startAfter(final BsonDocument startAfter) {
return this;
}
+ @Override
+ public ChangeStreamPublisher commandOption(final String name, final Object value) {
+ notNull("name", name);
+ isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTION_NAME.test(name));
+ overridingCommandOption(name, notNull("value", value));
+ return this;
+ }
+
@Override
ReadOperationCursor> asReadOperation(final int initialBatchSize) {
- return createChangeStreamOperation(codec, initialBatchSize);
+ return createChangeStreamOperation(codec, initialBatchSize, getOverridingCommandOptions());
}
@@ -177,8 +197,15 @@ Function, TimeoutSettings> getTimeoutSettings() {
return (operations -> operations.createTimeoutSettings(0, maxAwaitTimeMS));
}
- private ReadOperationCursor createChangeStreamOperation(final Codec codec, final int initialBatchSize) {
+ /**
+ * @param overridingCommandOptions This parameter exists to allow both {@code this} {@link ChangeStreamPublisherImpl},
+ * and the {@link BatchCursorPublisher} created and returned by {@link #withDocumentClass(Class)}
+ * to pass their own {@link #getOverridingCommandOptions()}.
+ */
+ private ReadOperationCursor createChangeStreamOperation(
+ final Codec codec, final int initialBatchSize, final Document overridingCommandOptions) {
return getOperations().changeStream(fullDocument, fullDocumentBeforeChange, pipeline, codec, changeStreamLevel, initialBatchSize,
- collation, comment, resumeToken, startAtOperationTime, startAfter, showExpandedEvents);
+ collation, comment, resumeToken, startAtOperationTime, startAfter, showExpandedEvents,
+ overridingCommandOptions);
}
}
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java
index e17b37bf959..ff62f2378b4 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java
@@ -33,7 +33,8 @@
import static com.mongodb.assertions.Assertions.notNull;
-final class DistinctPublisherImpl extends BatchCursorPublisher implements DistinctPublisher {
+final class DistinctPublisherImpl extends BatchCursorPublisher
+ implements InternalCommonBatchCursorPublisher, DistinctPublisher {
private final String fieldName;
private Bson filter;
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java
index e223b9daea9..4256c252130 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java
@@ -38,7 +38,8 @@
import static com.mongodb.assertions.Assertions.notNull;
-final class FindPublisherImpl extends BatchCursorPublisher implements FindPublisher {
+final class FindPublisherImpl extends BatchCursorPublisher
+ implements InternalCommonBatchCursorPublisher, FindPublisher {
private final FindOptions findOptions;
private Bson filter;
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java
new file mode 100644
index 00000000000..cc7da2f9b31
--- /dev/null
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java
@@ -0,0 +1,136 @@
+/*
+ * Copyright 2008-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.mongodb.reactivestreams.client.internal;
+
+import com.mongodb.ExplainVerbosity;
+import com.mongodb.client.cursor.TimeoutMode;
+import com.mongodb.client.model.Collation;
+import com.mongodb.lang.Nullable;
+import org.bson.BsonValue;
+import org.bson.Document;
+import org.bson.conversions.Bson;
+import org.reactivestreams.Publisher;
+
+import java.util.concurrent.TimeUnit;
+
+import static com.mongodb.assertions.Assertions.fail;
+
+/**
+ * The purpose of this interface is to ensure that all cursor publisher API interfaces that share methods
+ * have the signatures of those methods the same, and to help a maintainer to see which methods are shared.
+ * See {@code com.mongodb.reactivestreams.client.internal.InternalCommonBatchCursorPublisherTest}.
+ * This is a reactive counterpart to {@code com.mongodb.client.internal.InternalCommonIterable}.
+ *
+ * This class is not part of the public API and may be removed or changed at any time.
+ */
+public interface InternalCommonBatchCursorPublisher extends Publisher {
+ default Publisher first() {
+ throw fail();
+ }
+
+ default Publisher batchSize(int batchSize) {
+ throw fail();
+ }
+
+ default Publisher timeoutMode(TimeoutMode timeoutMode) {
+ throw fail();
+ }
+
+ default Publisher toCollection() {
+ throw fail();
+ }
+
+ default Publisher filter(@Nullable Bson filter) {
+ throw fail();
+ }
+
+ default Publisher limit(int limit) {
+ throw fail();
+ }
+
+ default Publisher skip(int skip) {
+ throw fail();
+ }
+
+ default Publisher maxTime(long maxTime, TimeUnit timeUnit) {
+ throw fail();
+ }
+
+ default Publisher maxAwaitTime(long maxAwaitTime, TimeUnit timeUnit) {
+ throw fail();
+ }
+
+ default Publisher collation(@Nullable Collation collation) {
+ throw fail();
+ }
+
+ default Publisher sort(@Nullable Bson sort) {
+ throw fail();
+ }
+
+ default Publisher noCursorTimeout(boolean noCursorTimeout) {
+ throw fail();
+ }
+
+ default Publisher comment(@Nullable String comment) {
+ throw fail();
+ }
+
+ default Publisher comment(@Nullable BsonValue comment) {
+ throw fail();
+ }
+
+ default Publisher hint(@Nullable Bson hint) {
+ throw fail();
+ }
+
+ default Publisher hintString(@Nullable String hint) {
+ throw fail();
+ }
+
+ default Publisher let(@Nullable Bson variables) {
+ throw fail();
+ }
+
+ default Publisher allowDiskUse(@Nullable Boolean allowDiskUse) {
+ throw fail();
+ }
+
+ default Publisher explain() {
+ throw fail();
+ }
+
+ default Publisher explain(ExplainVerbosity verbosity) {
+ throw fail();
+ }
+
+ default Publisher explain(Class explainResultClass) {
+ throw fail();
+ }
+
+ default Publisher explain(Class explainResultClass, ExplainVerbosity verbosity) {
+ throw fail();
+ }
+
+ default Publisher bypassDocumentValidation(@Nullable Boolean bypassDocumentValidation) {
+ throw fail();
+ }
+
+ default Publisher commandOption(String name, Object value) {
+ throw fail();
+ }
+}
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionNamesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionNamesPublisherImpl.java
index f07379d568c..17bc9bf4743 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionNamesPublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionNamesPublisherImpl.java
@@ -32,7 +32,7 @@
import static com.mongodb.assertions.Assertions.notNull;
import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE;
-public final class ListCollectionNamesPublisherImpl implements ListCollectionNamesPublisher {
+public final class ListCollectionNamesPublisherImpl implements InternalCommonBatchCursorPublisher, ListCollectionNamesPublisher {
private final ListCollectionsPublisherImpl wrapped;
private final Flux wrappedWithMapping;
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java
index 1f1e5f9d00a..f5920f7ead7 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java
@@ -35,7 +35,8 @@
import static com.mongodb.assertions.Assertions.notNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
-final class ListCollectionsPublisherImpl extends BatchCursorPublisher implements ListCollectionsPublisher {
+final class ListCollectionsPublisherImpl extends BatchCursorPublisher
+ implements InternalCommonBatchCursorPublisher, ListCollectionsPublisher {
private final boolean collectionNamesOnly;
private boolean authorizedCollections;
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java
index 5c7b408ef3f..39f30b1fe04 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java
@@ -33,7 +33,8 @@
import static com.mongodb.assertions.Assertions.notNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
-final class ListDatabasesPublisherImpl extends BatchCursorPublisher implements ListDatabasesPublisher {
+final class ListDatabasesPublisherImpl extends BatchCursorPublisher
+ implements InternalCommonBatchCursorPublisher, ListDatabasesPublisher {
private long maxTimeMS;
private Bson filter;
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java
index 851c56fcc54..8b193e93a59 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java
@@ -32,7 +32,8 @@
import static com.mongodb.assertions.Assertions.notNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
-final class ListIndexesPublisherImpl extends BatchCursorPublisher implements ListIndexesPublisher {
+final class ListIndexesPublisherImpl extends BatchCursorPublisher
+ implements InternalCommonBatchCursorPublisher, ListIndexesPublisher {
private long maxTimeMS;
private BsonValue comment;
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java
index c4c703e9774..456ee3ce72e 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java
@@ -34,7 +34,8 @@
import static com.mongodb.assertions.Assertions.notNull;
-final class ListSearchIndexesPublisherImpl extends BatchCursorPublisher implements ListSearchIndexesPublisher {
+final class ListSearchIndexesPublisherImpl extends BatchCursorPublisher
+ implements InternalCommonBatchCursorPublisher, ListSearchIndexesPublisher {
@Nullable
private Boolean allowDiskUse;
private long maxTimeMS;
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java
index 1e8e7fa223b..fdc3fc82964 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java
@@ -48,7 +48,8 @@
import static com.mongodb.assertions.Assertions.notNull;
@SuppressWarnings("deprecation")
-final class MapReducePublisherImpl extends BatchCursorPublisher implements com.mongodb.reactivestreams.client.MapReducePublisher {
+final class MapReducePublisherImpl extends BatchCursorPublisher
+ implements InternalCommonBatchCursorPublisher, com.mongodb.reactivestreams.client.MapReducePublisher {
private final String mapFunction;
private final String reduceFunction;
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSFindPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSFindPublisherImpl.java
index 41ee872c05e..47c4d24a957 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSFindPublisherImpl.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSFindPublisherImpl.java
@@ -21,6 +21,7 @@
import com.mongodb.lang.Nullable;
import com.mongodb.reactivestreams.client.FindPublisher;
import com.mongodb.reactivestreams.client.gridfs.GridFSFindPublisher;
+import com.mongodb.reactivestreams.client.internal.InternalCommonBatchCursorPublisher;
import org.bson.conversions.Bson;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
@@ -32,7 +33,7 @@
/**
* This class is not part of the public API and may be removed or changed at any time
*/
-public final class GridFSFindPublisherImpl implements GridFSFindPublisher {
+public final class GridFSFindPublisherImpl implements InternalCommonBatchCursorPublisher, GridFSFindPublisher {
private final FindPublisher wrapped;
GridFSFindPublisherImpl(final FindPublisher wrapped) {
diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/package-info.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/package-info.java
index 80d98a2346a..95984ab4550 100644
--- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/package-info.java
+++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/package-info.java
@@ -15,21 +15,37 @@
*/
/**
- * This packages contains classes for the reactive stream client implementation.
+ * This package contains classes for the reactive stream client implementation.
*
- * All API {@link org.reactivestreams.Publisher}s are
+ * All API {@link Publisher}s are
* cold,
* meaning that nothing happens until they are subscribed to.
- * So just creating a {@link org.reactivestreams.Publisher} won’t cause any network IO.
- * It’s not until {@link org.reactivestreams.Publisher#subscribe(org.reactivestreams.Subscriber)} is called that the driver executes the
- * operation.
+ * So just creating a {@link Publisher} won’t cause any network IO.
+ * It’s not until {@link Publisher#subscribe(Subscriber)} is called that the driver executes
+ * operations.
*
- * All API {@link org.reactivestreams.Publisher}s are unicast.
- * Each {@link org.reactivestreams.Subscription} to a {@link org.reactivestreams.Publisher} relates to a single MongoDB operation and its
- * {@link org.reactivestreams.Subscriber} will receive its own specific set of results.
+ * All API {@link Publisher}s are
+ * unicast:
+ * each {@link Subscription} to a {@link Publisher} relates to a separate set of
+ * operations, as identified by {@link CommandEvent#getOperationId()}
+ * (not to be confused with commands, as identified by {@link CommandEvent#getRequestId()}),
+ * and its {@link Subscriber} receives its own specific set of results.
+ * Usually, a single {@link Subscription} causes execution of a single operation, but in some cases, like
+ * {@link GridFSBucket#uploadFromPublisher(ClientSession, BsonValue, String, Publisher, GridFSUploadOptions)},
+ * it causes execution of multiple operations.
*/
@NonNullApi
package com.mongodb.reactivestreams.client;
import com.mongodb.lang.NonNullApi;
+// the following imports are used only in the API documentation comment, which `UnusedImports` does not take into account
+// CHECKSTYLE.OFF: UnusedImports
+import com.mongodb.client.gridfs.model.GridFSUploadOptions;
+import com.mongodb.event.CommandEvent;
+import com.mongodb.reactivestreams.client.gridfs.GridFSBucket;
+import org.bson.BsonValue;
+import org.reactivestreams.Publisher;
+import org.reactivestreams.Subscriber;
+import org.reactivestreams.Subscription;
+// CHECKSTYLE.ON: UnusedImports
diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java
new file mode 100644
index 00000000000..66db9427881
--- /dev/null
+++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java
@@ -0,0 +1,152 @@
+/*
+ * Copyright 2008-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.mongodb.reactivestreams.client;
+
+import com.mongodb.MongoClientSettings;
+import com.mongodb.client.MongoClient;
+import com.mongodb.event.ConnectionCheckedOutEvent;
+import com.mongodb.event.ConnectionPoolListener;
+import com.mongodb.internal.connection.TestCommandListener;
+import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient;
+import org.bson.BsonDocument;
+import org.bson.Document;
+import org.bson.conversions.Bson;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.reactivestreams.Publisher;
+import reactor.core.publisher.Mono;
+
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
+import java.util.function.Function;
+
+import static com.mongodb.ClusterFixture.TIMEOUT_DURATION;
+import static com.mongodb.client.model.Aggregates.merge;
+import static com.mongodb.client.model.Aggregates.out;
+import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException;
+import static com.mongodb.reactivestreams.client.Fixture.getMongoClientSettingsBuilder;
+import static java.util.Collections.emptyList;
+import static java.util.Collections.singletonList;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+final class AggregatePublisherIntegrationTest extends com.mongodb.client.AggregateIterableIntegrationTest {
+ @Override
+ protected MongoClient createClient(final MongoClientSettings settings) {
+ return new SyncMongoClient(settings);
+ }
+
+ @ParameterizedTest
+ @EnumSource(PublisherExecutor.class)
+ void commandOptionIsSeparateForSeparateSubscriptions(final PublisherExecutor publisherExecutor) throws Exception {
+ TestCommandListener commandListener = new TestCommandListener();
+ CountDownLatch commandOptionChanged = new CountDownLatch(1);
+ try (com.mongodb.reactivestreams.client.MongoClient client = MongoClients.create(getMongoClientSettingsBuilder()
+ .addCommandListener(commandListener)
+ .applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(new ConnectionPoolListener() {
+ @Override
+ public void connectionCheckedOut(final ConnectionCheckedOutEvent event) {
+ try {
+ // block executions
+ com.mongodb.assertions.Assertions.assertTrue(
+ commandOptionChanged.await(TIMEOUT_DURATION.toMillis(), MILLISECONDS));
+ } catch (InterruptedException e) {
+ throw interruptAndCreateMongoInterruptedException(null, e);
+ }
+ }
+ }))
+ .build())) {
+ AggregatePublisher publisher = client.getDatabase(NAMESPACE.getDatabaseName())
+ .getCollection(NAMESPACE.getCollectionName())
+ .aggregate(publisherExecutor.getPipeline());
+ publisher.commandOption("allowDiskUse", true);
+ CompletableFuture> firstSubscription = publisherExecutor.apply(publisher);
+ publisher.commandOption("allowDiskUse", false);
+ // unblock executions
+ commandOptionChanged.countDown();
+ firstSubscription.get(TIMEOUT_DURATION.toMillis(), MILLISECONDS);
+ assertTrue(publisherExecutor.getCommand(commandListener).getBoolean("allowDiskUse").getValue());
+ commandListener.reset();
+ CompletableFuture> secondSubscription = publisherExecutor.apply(publisher);
+ secondSubscription.get(TIMEOUT_DURATION.toMillis(), MILLISECONDS);
+ assertFalse(publisherExecutor.getCommand(commandListener).getBoolean("allowDiskUse").getValue());
+ }
+ }
+
+ private enum PublisherExecutor implements Function, CompletableFuture>> {
+ FIRST,
+ SUBSCRIBE,
+ SUBSCRIBE_WITH_OUT,
+ SUBSCRIBE_WITH_MERGE,
+ TO_COLLECTION_WITH_OUT,
+ TO_COLLECTION_WITH_MERGE,
+ EXPLAIN;
+
+ List getPipeline() {
+ switch (this) {
+ case SUBSCRIBE_WITH_OUT:
+ case TO_COLLECTION_WITH_OUT: {
+ return singletonList(out(NAMESPACE.getCollectionName()));
+ }
+ case SUBSCRIBE_WITH_MERGE:
+ case TO_COLLECTION_WITH_MERGE: {
+ return singletonList(merge(NAMESPACE.getCollectionName() + "Merged"));
+ }
+ default: {
+ return emptyList();
+ }
+ }
+ }
+
+ @Override
+ public CompletableFuture> apply(final AggregatePublisher> publisher) {
+ Publisher> publisherVariant;
+ switch (this) {
+ case FIRST: {
+ publisherVariant = publisher.first();
+ break;
+ }
+ case SUBSCRIBE:
+ case SUBSCRIBE_WITH_OUT:
+ case SUBSCRIBE_WITH_MERGE: {
+ publisherVariant = publisher;
+ break;
+ }
+ case TO_COLLECTION_WITH_OUT:
+ case TO_COLLECTION_WITH_MERGE: {
+ publisherVariant = publisher.toCollection();
+ break;
+ }
+ case EXPLAIN: {
+ publisherVariant = publisher.explain();
+ break;
+ }
+ default: {
+ throw com.mongodb.assertions.Assertions.fail();
+ }
+ }
+ return Mono.from(publisherVariant).toFuture();
+ }
+
+ BsonDocument getCommand(final TestCommandListener commandListener) {
+ return this == PublisherExecutor.EXPLAIN
+ ? commandListener.getCommandStartedEvent("explain").getCommand().getDocument("explain")
+ : commandListener.getCommandStartedEvent("aggregate").getCommand();
+ }
+ }
+}
diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamFunctionalTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamFunctionalTest.java
deleted file mode 100644
index 3b204150019..00000000000
--- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamFunctionalTest.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright 2008-present MongoDB, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.mongodb.reactivestreams.client;
-
-import com.mongodb.MongoClientSettings;
-import com.mongodb.client.AbstractChangeSteamFunctionalTest;
-import com.mongodb.client.MongoClient;
-import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient;
-
-public class ChangeStreamFunctionalTest extends AbstractChangeSteamFunctionalTest {
- @Override
- protected MongoClient createMongoClient(final MongoClientSettings mongoClientSettings) {
- return new SyncMongoClient(mongoClientSettings);
- }
-}
diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java
new file mode 100644
index 00000000000..702c579609a
--- /dev/null
+++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2008-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.mongodb.reactivestreams.client;
+
+import com.mongodb.MongoClientSettings;
+import com.mongodb.client.MongoClient;
+import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+
+import static com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient.disableWaitForBatchCursorCreation;
+import static com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient.enableWaitForBatchCursorCreation;
+
+/**
+ * Many of the tests from {@link com.mongodb.client.ChangeStreamProseTest} fail when run using {@link SyncMongoClient},
+ * because it does not have all the necessary implementations. Such tests are disabled.
+ */
+final class ChangeStreamProseTest extends com.mongodb.client.ChangeStreamProseTest {
+ @BeforeEach
+ void beforeEach() {
+ enableWaitForBatchCursorCreation();
+ }
+
+ @AfterEach
+ void afterEach() {
+ disableWaitForBatchCursorCreation();
+ }
+
+ @Override
+ protected MongoClient createClient(final MongoClientSettings settings) {
+ return new SyncMongoClient(settings);
+ }
+
+ @Test
+ @Disabled
+ @Override
+ protected void test07CursorNotClosed() {
+ }
+
+ @Test
+ @Disabled
+ @Override
+ protected void test11GetResumeTokenReturnsPostBatchResumeToken() {
+ }
+
+ @Test
+ @Disabled
+ @Override
+ protected void test13GetResumeTokenEqualsIdOfPreviousDocument() {
+ }
+
+ @Test
+ @Disabled
+ @Override
+ protected void test14GetResumeTokenReturnsStartAfter() {
+ }
+
+ @Test
+ @Disabled
+ @Override
+ protected void test14GetResumeTokenReturnsResumeAfter() {
+ }
+
+ @Test
+ @Disabled
+ @Override
+ protected void test15GetResumeTokenReturnsPostBatchResumeTokenAfterGetMore() {
+ }
+
+ @Test
+ @Disabled
+ @Override
+ protected void test19SplitChangeStreamEvents() {
+ }
+
+ @Test
+ @Disabled
+ @Override
+ protected void testNameSpaceTypeAbsentChangeStreamEvents() {
+ }
+}
diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java
new file mode 100644
index 00000000000..6aafc936862
--- /dev/null
+++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java
@@ -0,0 +1,159 @@
+/*
+ * Copyright 2008-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.mongodb.reactivestreams.client;
+
+import com.mongodb.MongoClientSettings;
+import com.mongodb.client.MongoClient;
+import com.mongodb.event.CommandStartedEvent;
+import com.mongodb.event.ConnectionCheckedOutEvent;
+import com.mongodb.event.ConnectionPoolListener;
+import com.mongodb.internal.connection.TestCommandListener;
+import com.mongodb.reactivestreams.client.internal.BatchCursorPublisher;
+import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient;
+import org.bson.BsonDocument;
+import org.bson.Document;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.reactivestreams.Publisher;
+import reactor.core.Disposable;
+import reactor.core.publisher.Mono;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+import static com.mongodb.ClusterFixture.TIMEOUT_DURATION;
+import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException;
+import static com.mongodb.reactivestreams.client.Fixture.getMongoClientSettingsBuilder;
+import static com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient.disableWaitForBatchCursorCreation;
+import static com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient.enableWaitForBatchCursorCreation;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+final class ChangeStreamPublisherIntegrationTest extends com.mongodb.client.ChangeStreamIterableIntegrationTest {
+ @BeforeEach
+ void beforeEach() {
+ enableWaitForBatchCursorCreation();
+ }
+
+ @AfterEach
+ void afterEach() {
+ disableWaitForBatchCursorCreation();
+ }
+
+ @Override
+ protected MongoClient createClient(final MongoClientSettings settings) {
+ return new SyncMongoClient(settings);
+ }
+
+ /**
+ * {@link ChangeStreamPublisher#withDocumentClass(Class)} returns a new {@link BatchCursorPublisher},
+ * which must handle batch size correctly.
+ *
+ * @param batchSizeBeforeWithDocumentClass Is never {@code false} because the corresponding reactive API usage is impossible.
+ */
+ @ParameterizedTest
+ @ValueSource(booleans = {true})
+ @Override
+ protected void batchSizeWorksForWithDocumentClass(final boolean batchSizeBeforeWithDocumentClass) {
+ super.batchSizeWorksForWithDocumentClass(batchSizeBeforeWithDocumentClass);
+ }
+
+ /**
+ * @see #batchSizeWorksForWithDocumentClass(boolean)
+ */
+ @Test
+ @Override
+ protected void commandOptionWorksForWithDocumentClass() {
+ super.commandOptionWorksForWithDocumentClass();
+ }
+
+ @ParameterizedTest
+ @EnumSource(PublisherExecutor.class)
+ void commandOptionIsSeparateForSeparateSubscriptions(final PublisherExecutor publisherExecutor) throws Exception {
+ TestCommandListener commandListener = new TestCommandListener();
+ CountDownLatch commandOptionChanged = new CountDownLatch(1);
+ try (com.mongodb.reactivestreams.client.MongoClient client = MongoClients.create(getMongoClientSettingsBuilder()
+ .addCommandListener(commandListener)
+ .applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(new ConnectionPoolListener() {
+ @Override
+ public void connectionCheckedOut(final ConnectionCheckedOutEvent event) {
+ try {
+ // block executions
+ com.mongodb.assertions.Assertions.assertTrue(
+ commandOptionChanged.await(TIMEOUT_DURATION.toMillis(), MILLISECONDS));
+ } catch (InterruptedException e) {
+ throw interruptAndCreateMongoInterruptedException(null, e);
+ }
+ }
+ }))
+ .build())) {
+ MongoDatabase database = client.getDatabase(NAMESPACE.getDatabaseName());
+ ChangeStreamPublisher publisher = database.getCollection(NAMESPACE.getCollectionName()).watch();
+ publisher.commandOption("allowDiskUse", true);
+ Disposable firstSubscription = publisherExecutor.apply(publisher);
+ try {
+ publisher.commandOption("allowDiskUse", false);
+ // unblock executions
+ commandOptionChanged.countDown();
+ waitForCommandAndAssert(commandListener, command -> assertTrue(command.getBoolean("allowDiskUse").getValue()));
+ } finally {
+ firstSubscription.dispose();
+ }
+ commandListener.reset();
+ Disposable secondSubscription = publisherExecutor.apply(publisher);
+ try {
+ waitForCommandAndAssert(commandListener, command -> assertFalse(command.getBoolean("allowDiskUse").getValue()));
+ } finally {
+ secondSubscription.dispose();
+ }
+ }
+ }
+
+ private static void waitForCommandAndAssert(final TestCommandListener commandListener, final Consumer asserter) throws Exception {
+ commandListener.waitForEvents(CommandStartedEvent.class, event -> event.getCommandName().equals("aggregate"), 1);
+ asserter.accept(commandListener.getCommandStartedEvent("aggregate").getCommand());
+ }
+
+ private enum PublisherExecutor implements Function, Disposable> {
+ FIRST,
+ SUBSCRIBE;
+
+ @Override
+ public Disposable apply(final ChangeStreamPublisher> publisher) {
+ Publisher> publisherVariant;
+ switch (this) {
+ case FIRST: {
+ publisherVariant = publisher.first();
+ break;
+ }
+ case SUBSCRIBE: {
+ publisherVariant = publisher;
+ break;
+ }
+ default: {
+ throw com.mongodb.assertions.Assertions.fail();
+ }
+ }
+ return Mono.from(publisherVariant).subscribe();
+ }
+ }
+}
diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java
index 6b81b1f42af..e934f3c1130 100644
--- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java
+++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java
@@ -137,4 +137,10 @@ public E explain(final Class explainResultClass) {
public E explain(final Class explainResultClass, final ExplainVerbosity verbosity) {
return requireNonNull(Mono.from(wrapped.explain(explainResultClass, verbosity)).contextWrite(CONTEXT).block(TIMEOUT_DURATION));
}
+
+ @Override
+ public AggregateIterable commandOption(final String name, final Object value) {
+ wrapped.commandOption(name, value);
+ return this;
+ }
}
diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java
index d078e176bc2..4bc5e39406f 100644
--- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java
+++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java
@@ -36,8 +36,6 @@
class SyncChangeStreamIterable extends SyncMongoIterable> implements ChangeStreamIterable {
private final ChangeStreamPublisher wrapped;
- @Nullable
- private Integer batchSize;
SyncChangeStreamIterable(final ChangeStreamPublisher wrapped) {
super(wrapped);
@@ -110,7 +108,6 @@ public ChangeStreamIterable resumeAfter(final BsonDocument resumeToken) {
@Override
public ChangeStreamIterable batchSize(final int batchSize) {
wrapped.batchSize(batchSize);
- this.batchSize = batchSize;
super.batchSize(batchSize);
return this;
}
@@ -129,11 +126,7 @@ public ChangeStreamIterable collation(@Nullable final Collation collation) {
@Override
public MongoIterable withDocumentClass(final Class clazz) {
- SyncMongoIterable result = new SyncMongoIterable<>(wrapped.withDocumentClass(clazz));
- if (batchSize != null) {
- result.batchSize(batchSize);
- }
- return result;
+ return new SyncMongoIterable<>(wrapped.withDocumentClass(clazz));
}
@Override
@@ -165,4 +158,10 @@ public ChangeStreamIterable showExpandedEvents(final boolean showExpandedEven
wrapped.showExpandedEvents(showExpandedEvents);
return this;
}
+
+ @Override
+ public ChangeStreamIterable commandOption(final String name, final Object value) {
+ wrapped.commandOption(name, value);
+ return this;
+ }
}
diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCursor.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCursor.java
index 4e0159f90d0..1f2481421fe 100644
--- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCursor.java
+++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCursor.java
@@ -106,7 +106,6 @@ public void onComplete() {
}
if (isWaitForBatchCursorCreationEnabled()) {
batchCursorCompletableFuture.get(TIMEOUT, TimeUnit.SECONDS);
- Hooks.resetOnEachOperator();
}
sleep(getSleepAfterCursorOpen());
} catch (InterruptedException e) {
@@ -117,6 +116,10 @@ public void onComplete() {
throw (RuntimeException) cause;
}
throw new RuntimeException(e);
+ } finally {
+ if (isWaitForBatchCursorCreationEnabled()) {
+ Hooks.resetOnEachOperator();
+ }
}
}
diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/ListCollectionNamesPublisherTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/ListCollectionNamesPublisherTest.java
new file mode 100644
index 00000000000..3139ed48025
--- /dev/null
+++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/ListCollectionNamesPublisherTest.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2008-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.mongodb.reactivestreams.client;
+
+import org.junit.jupiter.api.Test;
+
+import static com.mongodb.client.ListCollectionNamesIterableTest.EXPECTED_EXTRA_METHODS;
+import static com.mongodb.client.ListCollectionNamesIterableTest.EXPECTED_MISSING_METHODS;
+import static com.mongodb.client.ListCollectionNamesIterableTest.assertDeclaredMethodsMatch;
+
+final class ListCollectionNamesPublisherTest {
+ @Test
+ void declaredMethodsMatchListCollectionsPublisher() {
+ assertDeclaredMethodsMatch(
+ ListCollectionsPublisher.class,
+ EXPECTED_EXTRA_METHODS,
+ EXPECTED_MISSING_METHODS,
+ ListCollectionNamesPublisher.class);
+ }
+}
diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java
new file mode 100644
index 00000000000..65b6dcd5c59
--- /dev/null
+++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2008-present MongoDB, Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.mongodb.reactivestreams.client.internal;
+
+import com.mongodb.client.ListCollectionNamesIterableTest;
+import com.mongodb.client.internal.InternalCommonIterableTest;
+import com.mongodb.reactivestreams.client.AggregatePublisher;
+import com.mongodb.reactivestreams.client.ChangeStreamPublisher;
+import com.mongodb.reactivestreams.client.DistinctPublisher;
+import com.mongodb.reactivestreams.client.FindPublisher;
+import com.mongodb.reactivestreams.client.ListCollectionNamesPublisher;
+import com.mongodb.reactivestreams.client.ListCollectionsPublisher;
+import com.mongodb.reactivestreams.client.ListDatabasesPublisher;
+import com.mongodb.reactivestreams.client.ListIndexesPublisher;
+import com.mongodb.reactivestreams.client.ListSearchIndexesPublisher;
+import com.mongodb.reactivestreams.client.gridfs.GridFSFindPublisher;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.reactivestreams.Publisher;
+
+import java.lang.reflect.Method;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.stream.Stream;
+
+import static com.mongodb.client.internal.InternalCommonIterableTest.IS_PUBLIC_API;
+import static com.mongodb.client.internal.InternalCommonIterableTest.assertEachApiInterfaceImplMustImplementInternalCommonInterface;
+import static com.mongodb.client.internal.InternalCommonIterableTest.assertEachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonInterface;
+import static com.mongodb.client.internal.InternalCommonIterableTest.assertEachInternalCommonInterfaceMethodMustBeInAtLeastTwoApiInterfaces;
+import static com.mongodb.client.internal.InternalCommonIterableTest.findClasses;
+import static com.mongodb.client.internal.InternalCommonIterableTest.methodErasedSignatures;
+import static java.util.Arrays.stream;
+import static java.util.Comparator.comparing;
+import static java.util.stream.Collectors.toCollection;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+final class InternalCommonBatchCursorPublisherTest {
+ /**
+ * The relevant cursor publisher API interfaces. Implementations of most, but not all of them extend {@link BatchCursorPublisher}.
+ */
+ @SuppressWarnings("deprecation")
+ private static final Set> API_INTERFACES = Stream.of(
+ AggregatePublisher.class,
+ ChangeStreamPublisher.class,
+ DistinctPublisher.class,
+ FindPublisher.class,
+ ListCollectionsPublisher.class,
+ ListCollectionNamesPublisher.class,
+ ListDatabasesPublisher.class,
+ ListIndexesPublisher.class,
+ ListSearchIndexesPublisher.class,
+ com.mongodb.reactivestreams.client.MapReducePublisher.class,
+ GridFSFindPublisher.class).
+ collect(toCollection(() -> new TreeSet<>(comparing(Class::getName))));
+ private static Path codeSourcePath;
+
+ @BeforeAll
+ static void beforeAll() throws Exception {
+ codeSourcePath = Paths.get(BatchCursorPublisher.class.getProtectionDomain().getCodeSource().getLocation().toURI());
+ }
+
+ /**
+ * The relevant cursor publisher API interfaces must be listed explicitly in {@link #API_INTERFACES}.
+ *
+ * An interface is relevant if all the following is true:
+ *
+ * -
+ * it is {@code public};
+ * -
+ * it is not in an internal package;
+ * -
+ * it is subinterface of {@link Publisher}, but not {@link Publisher} itself;
+ * -
+ * it has a {@code public} method with the {@linkplain ListCollectionNamesIterableTest#erasedSignature(Method) erased signature}
+ * of a {@code public} method in {@link BatchCursorPublisher}, excluding the {@link Publisher} and {@link Object} methods.
+ *
+ */
+ @Test
+ void relevantApiInterfacesAreListedExplicitly() {
+ Set publisherMethodSignatures = methodErasedSignatures(Publisher.class);
+ Set objectMethodSignatures = methodErasedSignatures(Object.class);
+ Set cursorPublisherMarkingMethods = stream(BatchCursorPublisher.class.getMethods())
+ .map(ListCollectionNamesIterableTest::erasedSignature)
+ .filter(signature -> !publisherMethodSignatures.contains(signature) && !objectMethodSignatures.contains(signature))
+ .collect(toCollection(TreeSet::new));
+ assertEquals(API_INTERFACES, findClasses(codeSourcePath, IS_PUBLIC_API
+ .and(klass -> klass.isInterface())
+ .and(klass -> Publisher.class.isAssignableFrom(klass))
+ .and(klass -> methodErasedSignatures(klass).stream().anyMatch(cursorPublisherMarkingMethods::contains))),
+ "Either the explicit set of relevant interfaces or the code detecting them must be updated");
+ }
+
+ @Test
+ void relevantApiInterfacesMatchTheSyncInterfaces() {
+ Set expectedApiInterfaceSimpleNames = InternalCommonIterableTest.API_INTERFACES.stream()
+ .map(Class::getSimpleName)
+ .map(syncApiInterfaceName -> syncApiInterfaceName.substring(0, syncApiInterfaceName.length() - "Iterable".length()) + "Publisher")
+ .collect(toCollection(TreeSet::new));
+ Set actualApiInterfaceSimpleNames = API_INTERFACES.stream().map(Class::getSimpleName).collect(toCollection(TreeSet::new));
+ assertEquals(expectedApiInterfaceSimpleNames, actualApiInterfaceSimpleNames,
+ "The explicit set of relevant reactive interfaces must match that of the synchronous ones");
+ }
+
+ /**
+ * Each cursor publisher API interface implementation must implement {@link InternalCommonBatchCursorPublisher}.
+ */
+ @Test
+ void eachApiInterfaceImplMustImplementInternalCommonBatchCursorPublisher() {
+ assertEachApiInterfaceImplMustImplementInternalCommonInterface(codeSourcePath, API_INTERFACES, InternalCommonBatchCursorPublisher.class);
+ }
+
+ /**
+ * Each {@link InternalCommonBatchCursorPublisher} method must be in at least two cursor publisher API interfaces.
+ */
+ @Test
+ void eachInternalCommonBatchCursorPublisherMethodMustBeInAtLeastTwoApiInterfaces() {
+ assertEachInternalCommonInterfaceMethodMustBeInAtLeastTwoApiInterfaces(API_INTERFACES, InternalCommonBatchCursorPublisher.class);
+ }
+
+ /**
+ * Each cursor publisher API interface method shared with another cursor publisher API interface must be in {@link InternalCommonBatchCursorPublisher}.
+ */
+ @Test
+ void eachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonBatchCursorPublisher() {
+ assertEachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonInterface(API_INTERFACES, InternalCommonBatchCursorPublisher.class);
+ }
+}
diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala
index 74f5a909811..9ef3e7ac6d4 100644
--- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala
+++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala
@@ -107,4 +107,9 @@ case class SyncAggregateIterable[T](wrapped: AggregateObservable[T])
.explain[E](verbosity)(DefaultsTo.overrideDefault[E, org.mongodb.scala.Document], ClassTag(explainResultClass))
.toFuture()
.get()
+
+ override def commandOption(name: String, value: Object): AggregateIterable[T] = {
+ wrapped.commandOption(name, value)
+ this
+ }
}
diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala
index 087b558f72b..4342f3dd19d 100644
--- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala
+++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala
@@ -100,4 +100,9 @@ case class SyncChangeStreamIterable[T](wrapped: ChangeStreamObservable[T])
wrapped.showExpandedEvents(showExpandedEvents)
this
}
+
+ override def commandOption(name: String, value: Object): ChangeStreamIterable[T] = {
+ wrapped.commandOption(name, value)
+ this
+ }
}
diff --git a/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala
index a363ee21662..ccdd6a5ab41 100644
--- a/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala
+++ b/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala
@@ -263,6 +263,27 @@ case class AggregateObservable[TResult](private val wrapped: AggregatePublisher[
)(implicit e: ExplainResult DefaultsTo Document, ct: ClassTag[ExplainResult]): SingleObservable[ExplainResult] =
wrapped.explain[ExplainResult](ct, verbosity)
+ /**
+ * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies your needs.
+ * The behavior of this method is undefined if it is used to set any of the following:
+ * - a field from the following set:
+ * [[maxTime maxTimeMS]], `cursor`, [[[explain[ExplainResult](verbosity:com\.mongodb\.ExplainVerbosity)* explain]]],
+ * [[comment(comment:org\.mongodb\.scala\.bson\.BsonValue)* comment]], [[collation collation]];
+ * - a field that is configurable via means other than [[AggregateObservable]] methods;
+ * - a field that is also set via a different [[AggregateObservable]] method.
+ *
+ * @param name The name of the optional command field.
+ * @param value The value of the field specified by `name`.
+ * It is encoded via the configured `CodecRegistry`,
+ * which must have a codec for `org.bson.Document` regardless of the type of `value`.
+ * @return `this`.
+ * @since 5.17
+ */
+ def commandOption(name: String, value: Any): AggregateObservable[TResult] = {
+ wrapped.commandOption(name, value)
+ this
+ }
+
/**
* Requests [[AggregateObservable]] to start streaming data according to the specified aggregation pipeline.
*
diff --git a/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala
index 61136ca4fad..d5845babf58 100644
--- a/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala
+++ b/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala
@@ -205,5 +205,26 @@ case class ChangeStreamObservable[TResult](private val wrapped: ChangeStreamPubl
*/
def first(): SingleObservable[ChangeStreamDocument[TResult]] = wrapped.first()
+ /**
+ * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies your needs.
+ * The behavior of this method is undefined if it is used to set any of the following:
+ * - a field from the following set:
+ * `maxTimeMS`, `cursor`, `explain`,
+ * [[comment(comment:org\.mongodb\.scala\.bson\.BsonValue)* comment]];
+ * - a field that is configurable via means other than [[ChangeStreamObservable]] methods;
+ * - a field that is also set via a different [[ChangeStreamObservable]] method.
+ *
+ * @param name The name of the optional command field.
+ * @param value The value of the field specified by `name`.
+ * It is encoded via the configured `CodecRegistry`,
+ * which must have a codec for `org.bson.Document` regardless of the type of `value`.
+ * @return `this`.
+ * @since 5.17
+ */
+ def commandOption(name: String, value: Any): ChangeStreamObservable[TResult] = {
+ wrapped.commandOption(name, value)
+ this
+ }
+
override def subscribe(observer: Observer[_ >: ChangeStreamDocument[TResult]]): Unit = wrapped.subscribe(observer)
}
diff --git a/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala
index bd30396ac28..a3a2a1d52e6 100644
--- a/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala
+++ b/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala
@@ -48,6 +48,10 @@ class AggregateObservableSpec extends BaseSpec with MockitoSugar {
val batchSize = 10
val ct = classOf[Document]
val verbosity = ExplainVerbosity.QUERY_PLANNER
+ val stringCommandOptionName = "stringCommandOptionName"
+ val stringCommandOptionValue = "stringCommandOptionValue"
+ val intCommandOptionName = "intCommandOptionName"
+ val intCommandOptionValue = 1
observable.allowDiskUse(true)
observable.maxTime(duration)
@@ -60,6 +64,8 @@ class AggregateObservableSpec extends BaseSpec with MockitoSugar {
observable.explain[Document]()
observable.explain[Document](verbosity)
observable.timeoutMode(TimeoutMode.ITERATION)
+ observable.commandOption(stringCommandOptionName, stringCommandOptionValue)
+ observable.commandOption(intCommandOptionName, intCommandOptionValue)
verify(wrapper).allowDiskUse(true)
verify(wrapper).maxTime(duration.toMillis, TimeUnit.MILLISECONDS)
@@ -72,6 +78,8 @@ class AggregateObservableSpec extends BaseSpec with MockitoSugar {
verify(wrapper).explain(ct)
verify(wrapper).explain(ct, verbosity)
verify(wrapper).timeoutMode(TimeoutMode.ITERATION)
+ verify(wrapper).commandOption(stringCommandOptionName, stringCommandOptionValue)
+ verify(wrapper).commandOption(intCommandOptionName, intCommandOptionValue)
observable.toCollection()
verify(wrapper).toCollection
diff --git a/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala
index bcc4bfea815..0691bfa7e08 100644
--- a/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala
+++ b/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala
@@ -16,7 +16,6 @@
package org.mongodb.scala
-import com.mongodb.client.cursor.TimeoutMode
import com.mongodb.reactivestreams.client.ChangeStreamPublisher
import org.mockito.Mockito.{ verify, verifyNoMoreInteractions }
import org.mongodb.scala.bson.BsonTimestamp
@@ -54,6 +53,10 @@ class ChangeStreamObservableSpec extends BaseSpec with MockitoSugar {
val startAtTime = BsonTimestamp()
val collation = Collation.builder().locale("en").build()
val batchSize = 10
+ val stringCommandOptionName = "stringCommandOptionName"
+ val stringCommandOptionValue = "stringCommandOptionValue"
+ val intCommandOptionName = "intCommandOptionName"
+ val intCommandOptionValue = 1
observable.batchSize(batchSize)
observable.fullDocument(fullDocument)
@@ -63,6 +66,8 @@ class ChangeStreamObservableSpec extends BaseSpec with MockitoSugar {
observable.maxAwaitTime(duration)
observable.collation(collation)
observable.withDocumentClass(classOf[Int])
+ observable.commandOption(stringCommandOptionName, stringCommandOptionValue)
+ observable.commandOption(intCommandOptionName, intCommandOptionValue)
verify(wrapper).batchSize(batchSize)
verify(wrapper).fullDocument(fullDocument)
@@ -72,6 +77,8 @@ class ChangeStreamObservableSpec extends BaseSpec with MockitoSugar {
verify(wrapper).maxAwaitTime(duration.toMillis, TimeUnit.MILLISECONDS)
verify(wrapper).collation(collation)
verify(wrapper).withDocumentClass(classOf[Int])
+ verify(wrapper).commandOption(stringCommandOptionName, stringCommandOptionValue)
+ verify(wrapper).commandOption(intCommandOptionName, intCommandOptionValue)
verifyNoMoreInteractions(wrapper)
}
diff --git a/driver-sync/src/main/com/mongodb/client/AggregateIterable.java b/driver-sync/src/main/com/mongodb/client/AggregateIterable.java
index 032e1860244..49435d5175f 100644
--- a/driver-sync/src/main/com/mongodb/client/AggregateIterable.java
+++ b/driver-sync/src/main/com/mongodb/client/AggregateIterable.java
@@ -27,6 +27,7 @@
import com.mongodb.lang.Nullable;
import org.bson.BsonValue;
import org.bson.Document;
+import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import java.util.concurrent.TimeUnit;
@@ -279,4 +280,27 @@ public interface AggregateIterable extends MongoIterable {
* @mongodb.server.release 3.6
*/