@@ -24,11 +24,12 @@ import com.mongodb.client.model.Filters
2424import com.mongodb.client.model.TextSearchOptions
2525import com.mongodb.client.model.geojson.Geometry
2626import com.mongodb.client.model.geojson.Point
27+ import org.bson.BsonDocument
28+ import org.bson.BsonType
29+ import org.bson.conversions.Bson
2730import java.util.regex.Pattern
2831import kotlin.internal.OnlyInputTypes
2932import kotlin.reflect.KProperty
30- import org.bson.BsonType
31- import org.bson.conversions.Bson
3233
3334/* *
3435 * Filters extension methods to improve Kotlin interop
@@ -288,7 +289,7 @@ public object Filters {
288289 * @param filters the list of filters to and together
289290 * @return the filter
290291 */
291- public fun and (filters : Iterable <Bson ?>): Bson = Filters . and ( filters.filterNotNull() )
292+ public fun and (filters : Iterable <Bson ?>): Bson = combineFilters( Filters :: and , filters)
292293
293294 /* *
294295 * Creates a filter that performs a logical AND of the provided list of filters. Note that this will only generate
@@ -309,7 +310,7 @@ public object Filters {
309310 * @param filters the list of filters to and together
310311 * @return the filter
311312 */
312- public fun or (filters : Iterable <Bson ?>): Bson = Filters . or ( filters.filterNotNull() )
313+ public fun or (filters : Iterable <Bson ?>): Bson = combineFilters( Filters :: or , filters)
313314
314315 /* *
315316 * Creates a filter that preforms a logical OR of the provided list of filters.
@@ -352,7 +353,9 @@ public object Filters {
352353 *
353354 * @return the filter
354355 */
355- @JvmSynthetic @JvmName(" existsExt" ) public fun <T > KProperty<T?>.exists (): Bson = Filters .exists(path())
356+ @JvmSynthetic
357+ @JvmName(" existsExt" )
358+ public fun <T > KProperty<T?>.exists (): Bson = Filters .exists(path())
356359
357360 /* *
358361 * Creates a filter that matches all documents that contain the given property.
@@ -1216,4 +1219,18 @@ public object Filters {
12161219 * @return the filter
12171220 */
12181221 public fun jsonSchema (schema : Bson ): Bson = Filters .jsonSchema(schema)
1222+
1223+ private fun combineFilters (
1224+ combine : (List <Bson >) -> Bson ,
1225+ filters : Iterable <Bson ?>
1226+ ): Bson = filters
1227+ .filterNotNull()
1228+ .filterNot { bson -> bson is Map <* , * > && bson.isEmpty() }
1229+ .let { list ->
1230+ when (list.size) {
1231+ 0 -> BsonDocument ()
1232+ 1 -> list.first()
1233+ else -> combine(list)
1234+ }
1235+ }
12191236}
0 commit comments