Menu Docs

Retrieve Data

In this guide, you can learn how to retrieve data from your MongoDB database by using the Kotlin driver. You can perform read operations to retrieve data from MongoDB.

Read operations enable you to perform the following tasks:

  • Retrieve a subset of documents from your collection using a find operation

  • Perform transformations on retrieved documents from your collection using an aggregate operation

  • Monitorar alterações em tempo real em seu banco de dados usando change streams

The following sections include examples that demonstrate how you can manage customer orders for cans of paint. For each order, you keep track of the color and quantity, which corresponds to the color and qty fields in documents in the orders collection:

{ "_id": 1, "color": "purple", "qty": 10 }
{ "_id": 2, "color": "green", "qty": 8 }
{ "_id": 3, "color": "purple", "qty": 4 }
{ "_id": 4, "color": "green", "qty": 11 }

Esses dados são modelados pela seguinte classe de dados de Kotlin :

data class PaintOrder(
@BsonId val id: Int,
val qty: Int,
val color: String
)

Utilize a operação de localizar para recuperar um subconjunto dos seus dados existentes no MongoDB. Você pode especificar os dados a serem retornados, inclusive quais documentos devem ser recuperados, em que ordem devem ser recuperados e quantos devem ser recuperados.

To perform a find operation, call the find() method on an instance of a MongoCollection. This method searches a collection for documents that match the query filter you provide. For more information on how to specify a query, see the Especificar uma query guide.

You want to know which orders contain greater than 3, but less than 9 cans of paint.

Run the following code to find orders to match the criteria:

val filter = Filters.and(Filters.gt("qty", 3), Filters.lt("qty", 9))
val resultsFlow = collection.find(filter)
resultsFlow.collect { println(it) }
PaintOrder(id=2, qty=8, color=green)
PaintOrder(id=3, qty=4, color=purple)

To learn more about the Filters builder, see the Construtores de filtros guide.

To view a runnable find() example, see the Localizar vários documentos usage example.

Use aggregation operations to run an aggregation pipeline on your data. An aggregation pipeline is a multi-staged transformation that produces an aggregated result.

To perform an aggregation operation, call the aggregate() method on an instance of MongoCollection. This method accepts aggregation expressions to run in sequence. To perform aggregations, you can define aggregation stages that specify how to match documents, rename fields, and group values. To learn more, see the Agregação guide.

You want to know which paint color is the most popular by finding the color that is bought the most.

You can create an aggregation pipeline that performs the following actions:

  • Corresponder a todos os documentos na collection orders

  • Agrupar pedidos por cores

  • Resume o campo de quantidade por cor

  • Ordenar os resultados pela quantidade mais alta para a mais baixa

data class AggregationResult(@BsonId val id: String, val qty: Int)
val filter = Filters.empty()
val pipeline = listOf(
Aggregates.match(filter),
Aggregates.group(
"\$color",
Accumulators.sum("qty", "\$qty")
),
Aggregates.sort(Sorts.descending("qty"))
)
val resultsFlow = collection.aggregate<AggregationResult>(pipeline)
resultsFlow.collect { println(it) }
PaintOrder(id=2, qty=19, color=green)
PaintOrder(id=3, qty=14, color=purple)

To learn more about constructing aggregation pipelines, see Agregação in the Server manual.

To learn more about the methods mentioned on this page, see the following API Documentation: