I'm just getting to know the possibilities of Kotlin and mongoDB.
I am writing a method that returns the name of the street after the ID.
Everything works, but I find it quite sloppy.
Empty String initialization, returning more data from the collection than I would like. How do I straighten it? Could it be made into some expression body one-liner?

    fun getStreetNameByStreetId(id: String): String {
    val query = Query()
    var streetName = ""
        query, STREET_COLLECTION
    ) { document: Document ->
        streetName = document.getValue("name").toString()
    return streetName
  • \$\begingroup\$ I don't use mongo, but this doesn't look like it would even work. You modify streetName with an asynchronous callback, so you're returning the original empty String before the callback even has a chance to be called. e.g. stackoverflow.com/questions/57330766/… \$\endgroup\$
    – Tenfour04
    Oct 4, 2021 at 1:02

1 Answer 1


This is how it would look in Java:

public String getStreetNameByStreetId(String id) {
    Query streetNameByStreetId = Query.query(
    return mongoTemplate.find(streetNameByStreetId, Street.class)

I realize you are looking for how this would look in Kotlin, but it should look very similar. Also, for simple CRUD operations you might want to consider just using a MongoRepository and leveraging the Domain Specific Language (DSL).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.