0
class MongoRepo<E>(private val collection: MongoCollection<E>) : Repo<E> {

    override fun create(element: E): Boolean {
        collection.insertOne(element)
        return true
    }

    override fun read(): List<Item<E>> {
        return collection.find().map { element ->
            Item(element.toString(), element)
        }.toList()
    }

I created repository, where I insert new record in MongoDB, but how to get id of the created record in read function?

I need smth like this Item(recordId, element).

Unfortunate I can't change function structure, return type and also I can't store id in external variable or list.

1 Answers1

0
class MongoRepo<E>(private val collection: MongoCollection<E>) : Repo<E> {

    override fun create(element: E): Boolean {
        collection.insertOne(element)
        return true
    }

    override fun read(): List<Item<E>> {
        val idsDocuments = collection.withDocumentClass<Document>().find().distinct()
        return collection.find().mapIndexed { index, element ->
            val itemId = idsDocuments[index].values.elementAt(0).toString()
            Item(itemId, element)
        }.toList()
    }

I cast collection to Document and find ids.