@@ -24,11 +24,12 @@ import com.mongodb.client.model.Filters
24
24
import com.mongodb.client.model.TextSearchOptions
25
25
import com.mongodb.client.model.geojson.Geometry
26
26
import com.mongodb.client.model.geojson.Point
27
+ import org.bson.BsonDocument
28
+ import org.bson.BsonType
29
+ import org.bson.conversions.Bson
27
30
import java.util.regex.Pattern
28
31
import kotlin.internal.OnlyInputTypes
29
32
import kotlin.reflect.KProperty
30
- import org.bson.BsonType
31
- import org.bson.conversions.Bson
32
33
33
34
/* *
34
35
* Filters extension methods to improve Kotlin interop
@@ -288,7 +289,7 @@ public object Filters {
288
289
* @param filters the list of filters to and together
289
290
* @return the filter
290
291
*/
291
- public fun and (filters : Iterable <Bson ?>): Bson = Filters . and ( filters.filterNotNull() )
292
+ public fun and (filters : Iterable <Bson ?>): Bson = combineFilters( Filters :: and , filters)
292
293
293
294
/* *
294
295
* 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 {
309
310
* @param filters the list of filters to and together
310
311
* @return the filter
311
312
*/
312
- public fun or (filters : Iterable <Bson ?>): Bson = Filters . or ( filters.filterNotNull() )
313
+ public fun or (filters : Iterable <Bson ?>): Bson = combineFilters( Filters :: or , filters)
313
314
314
315
/* *
315
316
* Creates a filter that preforms a logical OR of the provided list of filters.
@@ -352,7 +353,9 @@ public object Filters {
352
353
*
353
354
* @return the filter
354
355
*/
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())
356
359
357
360
/* *
358
361
* Creates a filter that matches all documents that contain the given property.
@@ -1216,4 +1219,18 @@ public object Filters {
1216
1219
* @return the filter
1217
1220
*/
1218
1221
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
+ }
1219
1236
}
0 commit comments