Menu Docs
Página inicial do Docs
/ /

Encontrar documentos

In this guide, you can learn how to use the Kotlin driver to retrieve data from a MongoDB collection by using read operations. You can call the find() method to retrieve documents that match a set of criteria specified in a query filter.

Os exemplos neste guia utilizam a coleção do movies no banco de dados do sample_mflix a partir doconjunto de dados de amostra do Atlas. Para saber como criar um cluster gratuito do MongoDB Atlas e carregar os conjuntos de dados de amostra, consulte o guia Get Started.

A seguinte classe de dados Kotlin modela os documentos nesta coleção:

data class Movie(val title: String, val runtime: Int, val imdb: IMDB){
data class IMDB(val rating: Double)
}

The following Kotlin data class models the results returned by the examples in this guide:

data class Results(val title: String)

O método find() recupera documentos de uma coleção. Este método usa um filtro de query e retorna todos os documentos correspondentes. Um filtro de query é um documento que especifica os critérios que o driver usa para corresponder aos documentos da coleção.

Para saber mais sobre filtros de query, consulte o guia Especificar uma query .

O exemplo a seguir encadeia o método firstOrNull() à chamada de método find() para localizar o primeiro documento no qual o valor do campo name é "The Room":

val projectionFields= Projections.fields(
Projections.include(Movie::title.name, Movie::imdb.name),
Projections.excludeId()
)
val resultsFlow = collection.withDocumentClass<Results>()
.find(eq(Movie::title.name, "The Room"))
.projection(projectionFields)
.firstOrNull()
if (resultsFlow == null) {
println("No results found.");
} else {
println(resultsFlow)
}
Movie(title=The Room, runtime=99, imdb=IMDB(rating=3.7))

This example uses the find() method to find all documents in which the value of the runtime field is less than 15. The find() operation returns a FindFlow object, which you can iterate through by using the collect() method, as shown in the following example:

val projectionFields= Projections.fields(
Projections.include(Movie::title.name, Movie::imdb.name),
Projections.excludeId()
)
val resultsFlow = collection.withDocumentClass<Results>()
.find(lt(Movie::runtime.name, 15))
.projection(projectionFields)
resultsFlow.collect { println(it) }
Movie(title=Meshes of the Afternoon, runtime=14, imdb=IMDB(rating=8.0))
Movie(title=The Band Concert, runtime=9, imdb=IMDB(rating=7.9))
Movie(title=What's Opera, Doc?, runtime=7, imdb=IMDB(rating=8.3))
...

Observação

Localizar todos os documentos

Para encontrar todos os documentos em uma coleção, passe um filtro vazio para o método find() :

val resultsFlow = collection.withDocumentClass<Results>()
.find()

You can modify the behavior of the find() method by chaining methods to a FindFlow instance. The following table describes commonly used methods for modifying queries:

Método
Descrição

batchSize()

Limits the number of documents to return per batch. To learn more about batch size, see cursor.batchSize() in the MongoDB Server manual.

collation()

Sets the collation options for the query.

collect()

Processes each element in the flow and applies the given lambda.

comment()

Specifies a string to attach to the query. This can help you trace and interpret the operation in the server logs and in profile data.

first()

Returns the first document that matches the query or throws a MongoClientException if no matching documents exist.

firstOrNull()

Returns the first document that matches the query or null if no matching documents exist.

hint()

Specifies the index to use for the query.

limit()

Limits the number of documents to be returned from the query.

skip()

Sets the number of documents to skip.

sort()

Defines the sort criteria to apply to the query.

O exemplo a seguir encadeia o método limit() para limitar o número de documentos retornados pela query para 10:

val projectionFields= Projections.fields(
Projections.include(Movie::title.name, Movie::imdb.name),
Projections.excludeId()
)
val resultsFlow = collection.withDocumentClass<Results>()
.find()
.projection(projectionFields)
.limit(10)

For a full list of methods that modify the behavior of find(), see the FindFlow class in the Kotlin driver API documentation.

Para saber mais sobre filtros de queries, consulte Especificar uma query.

Para saber mais sobre qualquer um dos métodos ou tipos discutidos neste guia, consulte a seguinte documentação da API:

Voltar

Insira documentos

Nesta página