Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversKotlin Coroutine

Filters Builders

On this page

  • Overview
  • Comparison
  • Logical
  • Arrays
  • Elements
  • Evaluation
  • Bitwise
  • Geospatial

In this guide, you can learn how to use builders to specify filters for your queries in the MongoDB Kotlin driver.

Builders are classes provided by the MongoDB Kotlin driver that help you construct BSON objects. To learn more, see our guide on builders.

Filters are operations used to limit the results of a query based on specified conditions. Filters are a helpful tool to locate information that matches search conditions in a collection.

You can use filters in the following places:

  • As a parameter to the find() method

  • In a match stage of an aggregation pipeline

  • As a parameter to the deleteOne() or deleteMany() method

  • As a parameter to the updateOne() or updateMany() method

Some examples of results from queries with filters are:

  • Items that cost more than $0 but less than $25.

  • Foods that are both gluten-free and less than 500 calories.

  • A food critic review that mentions "spicy".

This guide shows you how to use builders with examples of the following types of operators:

  • Comparison

  • Logical

  • Arrays

  • Elements

  • Evaluation

  • Bitwise

  • Geospatial

The Filters class provides static factory methods for all the MongoDB query operators. Each method returns an instance of the BSON type, which you can pass to any method that expects a query filter.

Tip

For brevity, you may choose to import all methods of the Filters class statically:

import com.mongodb.client.model.Filters.*

Most of the Filter examples in this guide use the following sample collection paints:

{ "_id": 1, "color": "red", "qty": 5, "vendor": ["A"] }
{ "_id": 2, "color": "purple", "qty": 10, "vendor": ["C", "D"] }
{ "_id": 3, "color": "blue", "qty": 8, "vendor": ["B", "A"] }
{ "_id": 4, "color": "white", "qty": 6, "vendor": ["D"] }
{ "_id": 5, "color": "yellow", "qty": 11, "vendor": ["A", "B"] }
{ "_id": 6, "color": "pink", "qty": 5, "vendor": ["C"] }
{ "_id": 7, "color": "green", "qty": 8,"vendor": ["B", "C"] }
{ "_id": 8, "color": "orange", "qty": 7, "vendor": ["A", "D"] }

These documents in the paints collection are modeled by the following data class for use with the Kotlin driver:

data class PaintOrder(
@BsonId val id: Int,
val qty: Int,
val color: String,
val vendors: List<String> = mutableListOf()
)

The comparison filters include all operators that compare the value in a document to a specified value.

The Filters comparison operator methods include:

Comparison Method
Matches
eq()
values equal to a specified value.
values greater than a specified value.
values greater than or equal to a specified value.
values less than a specified value.
values less than or equal to a specified value.
values not equal to a specified value.
any of the values specified in an array.
none of the values specified in an array.
all the documents.

The following example creates a filter that matches all documents where the value of the qty field equals "5" in the paints collection:

val equalComparison = Filters.eq(PaintOrder::qty.name, 5)
val resultsFlow = collection.find(equalComparison)
resultsFlow.collect { println(it) }
PaintOrder(id=1, qty=5, color=red, vendors=[A])
PaintOrder(id=6, qty=5, color=pink, vendors=[C])

The following example creates a filter that matches all documents where the value of the qty field is greater than or equal to "10" in the paints collection:

val gteComparison = Filters.gte(PaintOrder::qty.name, 10)
val resultsFlow = collection.find(gteComparison)
resultsFlow.collect { println(it) }
PaintOrder(id=2, qty=10, color=purple, vendors=[C, D])
PaintOrder(id=5, qty=11, color=yellow, vendors=[A, B])

The following example creates a filter that matches all documents in the paints collection because the predicate is empty:

val emptyComparison = Filters.empty()
val resultsFlow = collection.find(emptyComparison)
resultsFlow.collect { println(it) }
PaintOrder(id=1, qty=5, color=red, vendors=[A])
PaintOrder(id=2, qty=10, color=purple, vendors=[C, D])
PaintOrder(id=3, qty=8, color=blue, vendors=[B, A])
PaintOrder(id=4, qty=6, color=white, vendors=[D])
PaintOrder(id=5, qty=11, color=yellow, vendors=[A, B])
PaintOrder(id=6, qty=5, color=pink, vendors=[C])
PaintOrder(id=7, qty=8, color=green, vendors=[B, C])
PaintOrder(id=8, qty=7, color=orange, vendors=[A, D])

The logical operators perform logical operations based on the conditions of the specified method.

The Filters logical operator methods include:

Logical Method
Matches
documents with the conditions of all the filters. This operator joins filters with a logical AND.
documents with the conditions of either filter. This operator joins filters with a logical OR.
documents that do not match the filter.
documents that fail to match both filters. This operator joins filters with a logical NOR.

The following example creates a filter that matches documents where the value of the qty field is greater than "8" or the value of the color field equals "pink" in the paints collection:

val orComparison = Filters.or(
Filters.gt(PaintOrder::qty.name, 8),
Filters.eq(PaintOrder::color.name, "pink")
)
val resultsFlow = collection.find(orComparison)
resultsFlow.collect { println(it) }
PaintOrder(id=2, qty=10, color=purple, vendors=[C, D])
PaintOrder(id=5, qty=11, color=yellow, vendors=[A, B])
PaintOrder(id=6, qty=5, color=pink, vendors=[C])

The array operators evaluate the array field in a document.

The Filters array operator methods include:

Array Method
Matches
documents if the array field contains every element specified in the query.
documents if an element in the array field matches all the specified conditions.
documents if the array field is a specified number of elements.

The following example matches documents with a vendors array containing both "A" and "D" in the paints collection:

val search = listOf("A", "D")
val allComparison = Filters.all(PaintOrder::vendors.name, search)
val resultsFlow = collection.find(allComparison)
resultsFlow.collect { println(it) }
PaintOrder(id=8, qty=7, color=orange, vendors=[A, D])

The elements operators evaluate the nature of a specified field.

The Filters elements operator methods include:

Elements Method
Matches
documents that have the specified field.
documents if a field is of the specified type.

The following example matches documents that have a qty field and its value does not equal "5" or "8" in the paints collection:

val existsComparison = Filters.and(Filters.exists(PaintOrder::qty.name), Filters.nin("qty", 5, 8))
val resultsFlow = collection.find(existsComparison)
resultsFlow.collect { println(it) }
PaintOrder(id=2, qty=10, color=purple, vendors=[C, D])
PaintOrder(id=4, qty=6, color=white, vendors=[D])
PaintOrder(id=5, qty=11, color=yellow, vendors=[A, B])
PaintOrder(id=8, qty=7, color=orange, vendors=[A, D])

The evaluation operators evaluate the value of any field in a document.

The Filters evaluation operator methods include:

Evaluation Method
Matches
documents where a modulo operation on the value of a field contain a specified result.
documents where values contain a specified regular expression.
documents which contain a specified full-text search expression.
documents which contain a specified JavaScript expression.

The following example matches documents that have a color field starting with the letter "p" in the paints collection:

val regexComparison = Filters.regex(PaintOrder::color.name, "^p")
val resultsFlow = collection.find(regexComparison)
resultsFlow.collect { println(it) }
PaintOrder(id=2, qty=10, color=purple, vendors=[C, D])
PaintOrder(id=6, qty=5, color=pink, vendors=[C])

The bitwise operators convert a number into its binary value to evaluate its bits.

The Filters bitwise operator methods include:

Bitwise Method
Matches
documents where the specified bits of a field are set (i.e. "1").
documents where the specified bits of a field are clear (i.e. "0").
documents where at least one of the specified bits of a field are set (i.e. "1").
documents where at least one of the specified bits of a field are clear (i.e. "0").

The following example matches documents that have a decimalValue field with bits set at positions of the corresponding bitmask "34" (i.e. "00100010") in this binary_numbers collection:

{ "_id": 9, "decimalValue": 54, "binaryValue": "00110110" }
{ "_id": 10, "decimalValue": 20, "binaryValue": "00010100" }
{ "_id": 11, "decimalValue": 68, "binaryValue": "1000100" }
{ "_id": 12, "decimalValue": 102, "binaryValue": "01100110" }
data class BinaryNumber(
@BsonId val id: Int,
val decimalValue: Int,
val binaryValue: String
)
val binaryCollection = database.getCollection<BinaryNumber>("binary_numbers")
val bitmask = 34.toLong() // 00100010 in binary
val bitsComparison = Filters.bitsAllSet(BinaryNumber::decimalValue.name, bitmask)
val resultsFlow = binaryCollection.find(bitsComparison)
resultsFlow.collect { println(it) }
BinaryNumber(id=1, decimalValue=54, binaryValue=00110110)
BinaryNumber(id=4, decimalValue=102, binaryValue=01100110)

The geospatial operators evaluate a specified coordinate and its relation to a shape or location.

The Filters geospatial operator methods include:

Geospatial Method
Matches
documents containing a GeoJSON geometry value that falls within a bounding GeoJSON geometry.
documents containing a coordinates value that exist within the specified box.
documents containing a coordinates value that exist within the specified polygon.
documents containing a coordinates value that exist within the specified circle.
geometries containing a geospatial data value (GeoJSON or legacy coordinate pairs) that exist within the specified circle, using spherical geometry.
geometries that intersect with a GeoJSON geometry. The 2dsphere index supports $geoIntersects.
geospatial objects in proximity to a point. Requires a geospatial index. The 2dsphere and 2d indexes support $near.
geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The 2dsphere and 2d indexes support $nearSphere.

The following example creates a filter that matches documents in which the point field contains a GeoJSON geometry that falls within the given Polygon in this stores collection:

{ "_id": 13, "coordinates": { "type": "Point", "coordinates": [2.0, 2.0] } }
{ "_id": 14, "coordinates": { "type": "Point", "coordinates": [5.0, 6.0] } }
{ "_id": 15, "coordinates": { "type": "Point", "coordinates": [1.0, 3.0] } }
{ "_id": 16, "coordinates": { "type": "Point", "coordinates": [4.0, 7.0] } }
data class Store(
@BsonId val id: Int,
val name: String,
val coordinates: Point
)
val collection = database.getCollection<Store>("stores")
val square = Polygon(listOf(
Position(0.0, 0.0),
Position(4.0, 0.0),
Position(4.0, 4.0),
Position(0.0, 4.0),
Position(0.0, 0.0)))
val geoWithinComparison = Filters.geoWithin(Store::coordinates.name, square)
val resultsFlow = collection.find(geoWithinComparison)
resultsFlow.collect { println(it) }
Store(id=13, name=Store 13, coordinates=Point{coordinate=Position{values=[2.0, 2.0]}})
Store(id=15, name=Store 15, coordinates=Point{coordinate=Position{values=[1.0, 3.0]}})
←  Aggregates BuildersIndexes Builders →