KMongo - a Kotlin toolkit for Mongo

Overview

Gitter Maven Central Apache2 license Build Status codebeat badge codecov Awesome Kotlin Badge Pure Kotlin

KMongo

KMongo logo

A Kotlin toolkit for Mongo

Documentation: https://litote.org/kmongo

Forum: https://groups.google.com/forum/#!forum/kmongo

Native and Lightweight

KMongo features are available via Kotlin extensions - you use transparently the core MongoDB java driver API (both sync and reactive streams (ie async) drivers are supported)

With complete reactive streams & async support

You can use extensions for reactive streams style, Kotlin Coroutines, Reactor or RxJava2.

Built-in Object Mapping

Object oriented programming is usually better - use Objects, not Maps. Powered by the native POJO Codec, the Jackson library or Kotlinx Serialization.

Type-safe queries

Have you already queried an Int field with a String value? With KMongo type-safe queries, avoid the type errors. Provided with an optional annotation processor.

Mongo shell queries

You can copy/paste your queries from the Mongo shell in your IDE. Write readable source code!

Contributors

Acknowledgment

KMongo uses an open source license gracefully provided by YourKit for monitoring and profiling.

Comments
  • jackson serializer and deserializer for UUID

    jackson serializer and deserializer for UUID

    I am interacting my kotlin program with a collection that has an id field of type UUID(subtype4), instead of type LUUID(subtype3), which is represented as java.util.UUID in the Kotlin program.

    The problem is that when I retrieve the object back from the db, I get a org.bson.types.Binary Object. It makes sense but I want it to be a 'java.util.UUID` object in the program.

    Is it possible to overwrite the existing object mapper to support such transformation?

    I have these two helper functions to transform from/to UUID and Binary object
            fun toStandardBinaryUUID(uuid: UUID): Binary {...}
            fun fromStandardBinaryUUID(binary: Binary): UUID {...}
    

    Thanks

    enhancement help wanted 
    opened by chakwok 17
  • Exception with null problems in

    Exception with null problems in "Property.path()"

    http://prntscr.com/o5h5gl

    MongoPlayerEntryHandler: https://gist.github.com/LartyHD/83a39b010c6976a6339032b4a5b6e4f1 PlayerId: https://gist.github.com/LartyHD/fcc75723df3582948504b6494635bc97

    opened by LartyHD 11
  • Serialization for a Mongo type using kotlinx-serialization and ktor

    Serialization for a Mongo type using kotlinx-serialization and ktor

    I'm trying to implement a custom serializer for the Point class from Mongo. I'm seeing this error: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is DOCUMENT

    
    import com.mongodb.client.model.geojson.Point
    import com.mongodb.client.model.geojson.Position
    import kotlinx.serialization.KSerializer
    import kotlinx.serialization.descriptors.PrimitiveKind
    import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
    import kotlinx.serialization.descriptors.SerialDescriptor
    import kotlinx.serialization.encoding.Decoder
    import kotlinx.serialization.encoding.Encoder
    
    object PointSerializer : KSerializer<Point> {
        override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Point", PrimitiveKind.STRING)
    
        override fun serialize(encoder: Encoder, value: Point) {
            val values = value.coordinates.values
            var source = ""
                values.forEach {
                 source += it.toString() + "\n"
            }
            print("source point: $source")
            encoder.encodeString(source)
        }
    
        override fun deserialize(decoder: Decoder): Point {
            val string = decoder.decodeString()
            val values = string.split("\n")
            val doubleValues = mutableListOf<Double>()
            for (value in values) {
                 doubleValues.add(value.toDouble())
            }
            println("doubles: $doubleValues")
            return Point(Position(doubleValues))
        }
    }
    

    The usage is this:

    import com.manla.PointSerializer
    import com.mongodb.client.model.geojson.Point
    import kotlinx.serialization.Contextual
    import kotlinx.serialization.Serializable
    
    @Serializable
    data class Address(
        val line1 : String,
        val line2 : String,
        val city : String,
        val state : String,
        val country : String,
        @Serializable(with = PointSerializer::class)
        @Contextual
        val location : Point
    )
    

    What am I doing wrong? :(

    opened by manideepl 10
  • Filters not working after upgrading to 4.4.0

    Filters not working after upgrading to 4.4.0

    After trying to upgrade from 4.2.8 (tested on 4.3.0, seems to work OK there) to 4.4.0 I am getting errors in my tests because the filters doesn't seem to work as they used to. Only change is the upgrade to my kmongo-coroutine version.

    Is there something in these filters that is expected to break between 4.3.0 and 4.4.0?

    val filter = and(
        or(
            MyClass::someId eq someId,
            MyClass::someOtherId eq someOtherId,
            MyClass::nestedObject / NestedClass::yetAnotherId eq yetAnotherId
        ),
            MyClass::nestedObject exists true
    )
    collection
        .find(clientSession, filter)
        .sort(descending(MyClass::lastModifiedDate))
        .toList()
    

    For instance I am now getting back documents that clearly does not have the "MyClass::nestedObject".

    opened by gjermundgaraba 9
  • kotlinx Serialization does nos support binary standard uuidRepresentation

    kotlinx Serialization does nos support binary standard uuidRepresentation

    Obvious error when not configured : image

    How I'm willing to solve it : image

    The issue is I don't seem to have the KMongo related codec and it gives codec errors. How could I set up the UUID representation and have the optimal codec provided by the useful KMongo.createClient() function in a clean way?

    opened by Lezzio 9
  • Kotlinx.Serialization: first level serialization is broken

    Kotlinx.Serialization: first level serialization is broken

    How to reproduce:

    1. Push a class with an instant to the Mongo collection
    2. Find from the mongo collection
    3. It should fail to deserialize

    Expected Behavior

    It should deserialize to the correct class

    Actual Behavior

    It fails to deserialize

    Additional case specific information:

    Java 11, OpenJDK. KMongo 4.2.1

    Mongo Collection State:

    db.schedulerJob.find()
    { "_id" : ObjectId("5fb7d2bfac8e4033d69c163f"), "startTime" : ISODate("2020-11-20T14:29:19.502Z"), "duration" : NumberLong(900000), "targetUserId" : "110433910835404800", "guildId" : "383210853270552578", "reason" : "Time's up!", "action" : "UNMUTE" }
    

    Interface:

    interface SchedulerJob {
        @Contextual @SerialName("_id") val id: Id<SchedulerJob>
        val action: Action
        @Contextual val startTime: Instant
        val duration: Long
        val targetUserId: String
        val guildId: String
    
        fun shouldBePersisted(): Boolean {
            return duration >= Duration.ofMinutes(15).toMillis()
        }
    
        suspend fun processJob()
    }
    

    Effective class:

    @Serializable
    class UnmuteSchedulerJob(
        @Contextual @SerialName("_id") override val id: Id<SchedulerJob> = newId(),
        @Contextual override val startTime: Instant = Instant.now(),
        override val duration: Long,
        override val targetUserId: String,
        override val guildId: String,
        val reason: String?
    ) : SchedulerJob {
        override val action: Action = Action.UNMUTE
    
        override suspend fun processJob() {
            val jda = KoinContextHandler.get().get<JDA>()
            val guild = jda.getGuildById(guildId) ?: return
    
            val moderationService = KoinContextHandler.get().get<IModerationService>()
    
            moderationService.unmute(targetUserId, guild, reason)
        }
    }
    

    Exception Log:

    Exception in thread "pool-3-thread-1" org.bson.BsonInvalidOperationException: readString can only be called when CurrentBSONType is STRING, not when CurrentBSONType is DATE_TIME.
    	at org.bson.AbstractBsonReader.verifyBSONType(AbstractBsonReader.java:690)
    	at org.bson.AbstractBsonReader.checkPreconditions(AbstractBsonReader.java:722)
    	at org.bson.AbstractBsonReader.readString(AbstractBsonReader.java:457)
    	at com.github.jershell.kbson.FlexibleDecoder.decodeString(BsonFlexibleDecoder.kt:114)
    	at kotlinx.serialization.encoding.AbstractDecoder.decodeStringElement(AbstractDecoder.kt:56)
    	at kotlinx.serialization.internal.AbstractPolymorphicSerializer.deserialize(AbstractPolymorphicSerializer.kt:52)
    	at kotlinx.serialization.encoding.Decoder$DefaultImpls.decodeSerializableValue(Decoding.kt:234)
    	at kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableValue(AbstractDecoder.kt:17)
    	at org.litote.kmongo.serialization.SerializationCodec.decode(SerializationCodec.kt:69)
    	at com.mongodb.internal.operation.CommandResultArrayCodec.decode(CommandResultArrayCodec.java:52)
    	at com.mongodb.internal.operation.CommandResultDocumentCodec.readValue(CommandResultDocumentCodec.java:60)
    	at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:87)
    	at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:42)
    	at org.bson.internal.LazyCodec.decode(LazyCodec.java:48)
    	at org.bson.codecs.BsonDocumentCodec.readValue(BsonDocumentCodec.java:104)
    	at com.mongodb.internal.operation.CommandResultDocumentCodec.readValue(CommandResultDocumentCodec.java:63)
    	at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:87)
    	at org.bson.codecs.BsonDocumentCodec.decode(BsonDocumentCodec.java:42)
    	at com.mongodb.internal.connection.ReplyMessage.<init>(ReplyMessage.java:51)
    	at com.mongodb.internal.connection.InternalStreamConnection.getCommandResult(InternalStreamConnection.java:477)
    	at com.mongodb.internal.connection.InternalStreamConnection.access$1000(InternalStreamConnection.java:78)
    	at com.mongodb.internal.connection.InternalStreamConnection$2$1.onResult(InternalStreamConnection.java:462)
    	at com.mongodb.internal.connection.InternalStreamConnection$2$1.onResult(InternalStreamConnection.java:440)
    	at com.mongodb.internal.connection.InternalStreamConnection$MessageHeaderCallback$MessageCallback.onResult(InternalStreamConnection.java:745)
    	at com.mongodb.internal.connection.InternalStreamConnection$MessageHeaderCallback$MessageCallback.onResult(InternalStreamConnection.java:712)
    	at com.mongodb.internal.connection.InternalStreamConnection$5.completed(InternalStreamConnection.java:582)
    	at com.mongodb.internal.connection.InternalStreamConnection$5.completed(InternalStreamConnection.java:579)
    	at com.mongodb.internal.connection.AsynchronousChannelStream$BasicCompletionHandler.completed(AsynchronousChannelStream.java:250)
    	at com.mongodb.internal.connection.AsynchronousChannelStream$BasicCompletionHandler.completed(AsynchronousChannelStream.java:233)
    	at java.base/sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:127)
    	at java.base/sun.nio.ch.Invoker.invokeDirect(Invoker.java:158)
    	at java.base/sun.nio.ch.UnixAsynchronousSocketChannelImpl.implRead(UnixAsynchronousSocketChannelImpl.java:562)
    	at java.base/sun.nio.ch.AsynchronousSocketChannelImpl.read(AsynchronousSocketChannelImpl.java:277)
    	at java.base/sun.nio.ch.AsynchronousSocketChannelImpl.read(AsynchronousSocketChannelImpl.java:298)
    	at com.mongodb.internal.connection.AsynchronousSocketChannelStream$AsynchronousSocketChannelAdapter.read(AsynchronousSocketChannelStream.java:144)
    	at com.mongodb.internal.connection.AsynchronousChannelStream.readAsync(AsynchronousChannelStream.java:118)
    	at com.mongodb.internal.connection.AsynchronousChannelStream.readAsync(AsynchronousChannelStream.java:107)
    	at com.mongodb.internal.connection.InternalStreamConnection.readAsync(InternalStreamConnection.java:579)
    	at com.mongodb.internal.connection.InternalStreamConnection.access$1100(InternalStreamConnection.java:78)
    	at com.mongodb.internal.connection.InternalStreamConnection$MessageHeaderCallback.onResult(InternalStreamConnection.java:702)
    	at com.mongodb.internal.connection.InternalStreamConnection$MessageHeaderCallback.onResult(InternalStreamConnection.java:687)
    	at com.mongodb.internal.connection.InternalStreamConnection$5.completed(InternalStreamConnection.java:582)
    	at com.mongodb.internal.connection.InternalStreamConnection$5.completed(InternalStreamConnection.java:579)
    	at com.mongodb.internal.connection.AsynchronousChannelStream$BasicCompletionHandler.completed(AsynchronousChannelStream.java:250)
    	at com.mongodb.internal.connection.AsynchronousChannelStream$BasicCompletionHandler.completed(AsynchronousChannelStream.java:233)
    	at java.base/sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:127)
    	at java.base/sun.nio.ch.UnixAsynchronousSocketChannelImpl.finishRead(UnixAsynchronousSocketChannelImpl.java:439)
    	at java.base/sun.nio.ch.UnixAsynchronousSocketChannelImpl.finish(UnixAsynchronousSocketChannelImpl.java:191)
    	at java.base/sun.nio.ch.UnixAsynchronousSocketChannelImpl.onEvent(UnixAsynchronousSocketChannelImpl.java:213)
    	at java.base/sun.nio.ch.EPollPort$EventHandlerTask.run(EPollPort.java:306)
    	at java.base/sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112)
    	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    	at java.base/java.lang.Thread.run(Thread.java:834)
    
    opened by dondish 9
  • kotlin data class can not be decoded

    kotlin data class can not be decoded

    data class ShipDetail(
        var _id: String? = null,
        var order_id: String? = null)
    
    val collection = database.getCollection<ShipDetail>("ship_detail")
    var r = collection.findOne();
    

    produce exception:

    Exception in thread "main" org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class ShipDetail. at org.bson.codecs.configuration.CodecCache.getOrThrow(CodecCache.java:46) at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:63) at org.bson.codecs.configuration.ProvidersCodecRegistry.get(ProvidersCodecRegistry.java:37) at com.mongodb.FindIterableImpl.createQueryOperation(FindIterableImpl.java:228) at com.mongodb.FindIterableImpl.execute(FindIterableImpl.java:224) at com.mongodb.FindIterableImpl.first(FindIterableImpl.java:205) at org.litote.kmongo.ExtensionsKt.findOne(extensions.kt:163) at org.litote.kmongo.ExtensionsKt.findOne$default(extensions.kt:162)

    opened by frzleaf 9
  • @Transient not working

    @Transient not working

    Hello,

    I'm actually working on Kmongo which is a nice lib btw, however I've noticed a bug or I think it is one.

    here is my class:

    import kotlinx.serialization.Serializable
    
    @Serializable
    data class Person(val firstname: String, val lastname: String){
    
        val fullName: String
            get() = "${lastname} ${firstname}"
    }
    

    The computed value fullName is inserted in my mongo collection. I've tried to put @Transient, it's not working and I've got an inspection message saying this annotation is redundant because this variable has no backing field. (Property does not have backing field which makes it non-serializable and therefore @Transient is redundant)

    Thank you in advance.

    opened by yoobi 8
  • Find select field

    Find select field

    I have nations with settlements with members, I'm trying to get all of the members of the nation through the settlements.

            val members: List<SLPlayerId> = Settlement.COL
                .find(Settlement::nation eq id).projection(Settlement::members)
                .map { it.members }
                .flatten()
    

    This gives me this error:

    [08:01:22 ERROR]: [SLCore] [ACF] Caused by: com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException: Instantiation of [simple type, class net.starlegacy.slcore.mongo.Settlement] value failed for JSON property territory due to missing (therefore NULL) value for creator parameter territory which is a non-nullable type
    [08:01:22 ERROR]: [SLCore] [ACF]  at [Source: de.undercouch.bson4jackson.io.LittleEndianInputStream@24d5132b; pos: 148] (through reference chain: net.starlegacy.slcore.mongo.Settlement["territory"])
    

    Is there a way to get the value without attempting to construct the whole object?

    opened by MicleBrick 8
  • The problem is in new versions of KMongo when working with Spring

    The problem is in new versions of KMongo when working with Spring

    I am creating a telegram bot using Kotlin, Spring and KMongo While I was working on the KMongo 4.3.0 version, everything worked, but as soon as I try to upgrade to the higher versions, I get an error

    org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webHookController' defined in file [C:\Users\krugl\IdeaProjects\menshikova_bot\build\classes\kotlin\main\kartohhka\menshikova\bot\WebHookController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'telegramBot' defined in kartohhka.menshikova.bot.appconfig.BotConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [kartohhka.menshikova.bot.appconfig.botapi.MenshikovaTelegramBot]: Factory method 'telegramBot' threw exception; nested exception is java.lang.NoClassDefFoundError: org/bson/internal/CodecRegistryHelper
    	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:953) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.16.jar:5.3.16]
    	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.16.jar:5.3.16]
    	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.4.jar:2.6.4]
    	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:740) ~[spring-boot-2.6.4.jar:2.6.4]
    	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:415) ~[spring-boot-2.6.4.jar:2.6.4]
    	at org.springframework.boot.SpringApplication.run(SpringApplication.java:303) ~[spring-boot-2.6.4.jar:2.6.4]
    	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1312) ~[spring-boot-2.6.4.jar:2.6.4]
    	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1301) ~[spring-boot-2.6.4.jar:2.6.4]
    	at kartohhka.menshikova.bot.MenshikovaBotApplicationKt.main(MenshikovaBotApplication.kt:21) ~[main/:na]
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    	at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    	at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.6.4.jar:2.6.4]
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'telegramBot' defined in kartohhka.menshikova.bot.appconfig.BotConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [kartohhka.menshikova.bot.appconfig.botapi.MenshikovaTelegramBot]: Factory method 'telegramBot' threw exception; nested exception is java.lang.NoClassDefFoundError: org/bson/internal/CodecRegistryHelper
    	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:486) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1352) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1195) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1389) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1309) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791) ~[spring-beans-5.3.16.jar:5.3.16]
    	... 24 common frames omitted
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [kartohhka.menshikova.bot.appconfig.botapi.MenshikovaTelegramBot]: Factory method 'telegramBot' threw exception; nested exception is java.lang.NoClassDefFoundError: org/bson/internal/CodecRegistryHelper
    	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.16.jar:5.3.16]
    	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.16.jar:5.3.16]
    	... 38 common frames omitted
    Caused by: java.lang.NoClassDefFoundError: org/bson/internal/CodecRegistryHelper
    	at com.mongodb.client.internal.MongoClientImpl.<init>(MongoClientImpl.java:79) ~[mongodb-driver-sync-4.4.2.jar:na]
    	at com.mongodb.client.internal.MongoClientImpl.<init>(MongoClientImpl.java:65) ~[mongodb-driver-sync-4.4.2.jar:na]
    	at com.mongodb.client.MongoClients.create(MongoClients.java:108) ~[mongodb-driver-sync-4.4.2.jar:na]
    	at org.litote.kmongo.KMongo.createClient(KMongo.kt:76) ~[kmongo-core-4.7.1.jar:na]
    	at kartohhka.menshikova.bot.controller.DBController.<clinit>(DBController.kt:18) ~[main/:na]
    	at kartohhka.menshikova.bot.appconfig.BotConfig.telegramBot(BotConfig.kt:22) ~[main/:na]
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    	at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
    	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.16.jar:5.3.16]
    	... 39 common frames omitted
    Caused by: java.lang.ClassNotFoundException: org.bson.internal.CodecRegistryHelper
    	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) ~[na:na]
    	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[na:na]
    	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[na:na]
    	... 50 common frames omitted
    
    
    Process finished with exit code 0
    
    

    Dependencies

    testImplementation(kotlin("test"))
       implementation("org.springframework.boot:spring-boot-starter-web")
       implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
       implementation("org.jetbrains.kotlin:kotlin-reflect")
       implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
       implementation ("org.telegram:telegrambots-spring-boot-starter:6.1.0")
       implementation ("org.telegram:telegrambots-meta:6.1.0")
       implementation("org.projectlombok:lombok:1.18.24")
       testImplementation ("de.flapdoodle.embed:de.flap-doodle.embed.mongo:3.4.3")
       implementation ("org.springframework.boot:spring-boot-configuration-processor:2.7.4")
       implementation ("org.springframework.boot:spring-boot-starter-data-mongodb:2.7.4")
       developmentOnly("org.springframework.boot:spring-boot-devtools")
       testImplementation("org.springframework.boot:spring-boot-starter-test")
       
       implementation("org.mongodb:bson:4.7.1")
    
       implementation("com.vdurmont:emoji-java:5.1.1")
       implementation ("org.springframework.boot:spring-boot-maven-plugin:2.7.4")
    

    DBController

    object DBController {
        
        private val client = KMongo.createClient() //get com.mongodb.MongoClient new instance
    
        private val database = client.getDatabase("menshikova_bot") //normal java driver usage
    
        private val botDoc = database.getCollection<BotConf>("botconf")
        private val userDoc = database.getCollection<User>("user")
    
        fun getBotDoc(): MongoCollection<BotConf> {
            return botDoc
        }
    
        fun getUserDoc(): MongoCollection<User> {
            return userDoc
        }
    }
    
    opened by KaRtoHHka 7
  • Typed Aggregation Lookup for nested Objects

    Typed Aggregation Lookup for nested Objects

    II have aggregation such as:

    match(
            and(
                HistoryEventWrapper<HistoricProcessInstance>::submittedByClusterName eq clusterName,
                HistoryEventWrapper<HistoricProcessInstance>::submittedByEngineName eq engineName
            )
        ),
        replaceRoot(HistoryEventWrapper<HistoricProcessInstance>::event),
        match(processInstanceFilter)
    

    and i want to run a lookup after the match(processInstanceFilter)

    where my lookup is something like:

    lookup(
                collections.historicVariableInstanceColl.namespace.collectionName,
                listOf(
                    HistoricProcessInstance::processInstanceId.variableDefinition()
                ),
                HistoricProcessInstance::variableInstances,
                match(
                    expr(
                        and(
                            HistoryEventWrapper<HistoricVariableInstance>::event / HistoricVariableInstance::processInstanceId eq HistoricProcessInstance::processInstanceId.variable  // this does not work
                        )
                    )
                )
            )
    

    This seems to create a error due to the nesting path within the and()

    Command failed with error 16412 (Location16412): 'FieldPath field names may not contain '.'.'
    

    I there a way to do this with the nested objects and typed queries?

    Thanks!

    opened by StephenOTT 7
  • Typed enum queries ignore @SerialName using coroutine client

    Typed enum queries ignore @SerialName using coroutine client

    Hello, and Happy Holidays!

    Related fix for #331 only works for the sync client. Described issues happen starting with 4.5.0 and affects latest 4.8.0 as well

    Possible a common problem with #343

    Steps to reproduce:

    Take the Issue331EnumSerialName test case from the PR and add it also into kmongo-coroutine-serialization/src/test/kotlin and the bug will manifest the same way as described in the old issue.

    Not sure if other async modules are impacted but it seems they share similar code paths.

    opened by krodyrobi 0
  • replaceOneById doesn't use a custom CodecRegistry

    replaceOneById doesn't use a custom CodecRegistry

    replaceOneById -> replaceOneWithoutId -> KMongoUtil.filterIdToBson -> SerializationClassMappingTypeService::filterIdToBson

    I think in this line, it should access a custom codec registry that a user registered by MongoCollection::withCodecRegistry(registry). Because of this, it fails to find a codec and fails serialization.

    opened by piglovesyou 0
  • Support setWindowFields in aggregation DSL

    Support setWindowFields in aggregation DSL

    Many of the possible aggregation stages, like group and project, have built-in methods to generate the appropriate BSON. The setWindowFields stage is missing, making it difficult to use from KMongo.

    opened by tradeJmark 0
  • Support for `findOneAndUpdate` with an aggregation pipeline

    Support for `findOneAndUpdate` with an aggregation pipeline

    According to https://www.mongodb.com/docs/upcoming/reference/method/db.collection.findOneAndUpdate/ findOneAndUpdate also supports defining an aggregation pipeline for the update.

    This is also supported by the java client, it's the variant taking a List<Bson> as a parameter for the update.

    enhancement 
    opened by mervyn-mccreight 0
  • Behavior of `evaluate` when no results are available

    Behavior of `evaluate` when no results are available

    What does evaluate do when no results are found?

    Ideally, I'd like it to call the lambda with an empty sequence:

    myCollection.find(…).evaluate {
        println(isEmpty()) // prints 'true'
    }
    

    In case this is the current behavior, would it be possible to add a sentence to make it clear in evaluate's documentation?

    opened by CLOVIS-AI 4
  • KMongo unable to save field with name

    KMongo unable to save field with name "isClosed" and type "String"

    Hi Team,

    I have observed that when we are trying to save a document using kmongo methods, field "isClosed" is ignored if it is of type String. However same field name with Boolean data type works. Also, if document contains an additional field with name "closed" and type String along with "isClosed", it doesn't save "closed" and rather saves "isClosed". We have a use case where we need to persist isClosed field name but facing issue.

    Is this something which is expected or isClosed as string is some keyword ?

    bug waiting third party release 
    opened by himanshuvaish93 3
Releases(kmongo-4.8.0)
  • kmongo-4.8.0(Nov 27, 2022)

    • #382 Added possibility to customize ObjectMapper's KotlinModule
    • #383 filterIdToBson doesn't filter id field (only filters '_id' named field)

    This version should be the last release in the KMongo repo (if no critical bug found).

    A MR is planned to move the code into the MongoDB repository 🍾🥂

    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.7.2(Oct 28, 2022)

  • kmongo-4.7.1(Sep 10, 2022)

    • #365 CoroutineCollection.save doesn't use specified Serializer (kotlinx.serialization)
    • #369 Add client metadata for KMongo
    • #371 Filtering for enum with custom value fails with Jackson serialization
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.7.0(Aug 8, 2022)

    • https://github.com/Litote/kmongo/issues/356 Update unsigned integers
    • https://github.com/Litote/kmongo/issues/357 Broken type safety checking on / : this change is not backward compatible - use new % operator if you get compiler error - see https://litote.org/kmongo/typed-queries/#unsafe-nested-properties-and-operator
    • https://github.com/Litote/kmongo/issues/358 add uuid jackson documentation
    • https://github.com/Litote/kmongo/issues/360 Java driver 4.7 upgrade
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.6.1(Jun 19, 2022)

    • #299 Add pos function
    • #352 Polymorphic types, easy way to select by type (___type field)
    • #353 Add support for $arrayElemAt, $ifNull, $dateToString and typesafe $lookup shortcut
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.6.0(May 14, 2022)

    • #333 Support $count aggregation operator
    • #335 Extend usage of dayOfYear, Month and Week to ObjectID
    • #345 test: use latest flapdoodle version & allow to select the mongo server test version
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.5.1(Mar 31, 2022)

    • #321 Reset all mappers, including those derived from the primary BSON mappers
    • #327 CoroutineCollection.save has no client session variant
    • #329 Fix CoroutineCollection.createIndexes
    • #331 Typed queries ignore @SerialName annotations on enum values, regression from 4.4.0
    • #332 Adding ability to use setTo in updateOneById
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.5.0(Feb 12, 2022)

    • #312 remove sl4j-simple dependency from kmongo-flapdoodle
    • #319 ObjectMappingConfiguration.serializeNull = false & save/replace persist null
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.4.0(Nov 21, 2021)

    • #242 allow to not serialize null values for jackson & kotlinx.serialization
    • #294 document mapping service property
    • #301 kotlinx-serialization: add temporal serialization from and to numbers instead of only string and date
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.3.0(Sep 11, 2021)

    • #283 support 'id' property in model objects (using -D"kmongo.id.property.support.enabled"=true)
    • #291 kotlinx Serialization does nos support binary standard uuidRepresentation
    • #293 mongodb 5 support
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.2.8(Jun 19, 2021)

  • kmongo-4.2.7(May 9, 2021)

  • kmongo-4.2.6(Apr 11, 2021)

  • kmongo-4.2.5(Mar 21, 2021)

    • #267 Coroutine and reactive streams modules missing projection extension
    • #268 [jackson mapping] Ids that wrap ObjectIds are not being properly deserialized for an inherited class
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.2.4(Jan 30, 2021)

    • #251 add setValueOnInsert
    • #253 returning null on "let" property for lookup returns exception
    • #257 improves error message when serializing BsonField
    • #258 kotlinx.serialization - improves the doc when serializing a list of Id
    • #259 deleteOneById() has no clientSession version
    • #262 string as a lookup variable
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.2.3(Dec 6, 2020)

  • kmongo-4.2.2(Nov 27, 2020)

  • kmongo-4.2.1(Nov 22, 2020)

  • kmongo-4.2.0(Nov 8, 2020)

  • kmongo-4.1.3(Oct 13, 2020)

  • kmongo-4.1.2(Aug 19, 2020)

  • kmongo-4.1.1(Aug 18, 2020)

    • #222 Kotlin 1.4 support 🎉

    Breaking changes for kotlinx.serialization around @SerialName usage:

    • Need to add on annotated property @SerialName("_id") the @MongoId annotation: see https://litote.org/kmongo/object-mapping/#set-your-_id

    • Need to add on annotated property @SerialName("myProperty") the @MongoProperty annotation: see https://litote.org/kmongo/object-mapping/#workaround-around-typed-queries-and-serialname

    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.1.0(Aug 12, 2020)

    • #213 Unnecessary suspend modifier for 'CoroutineCollection.aggregate'
    • #215 implements regex on arrays
    • #218 support kotlinx.serialization for json
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.0.3(Jul 10, 2020)

  • kmongo-4.0.2(Jun 2, 2020)

  • kmongo-4.0.1(May 12, 2020)

    • #194 kotlin.x external serializers not properly handled
    • #196 kotlin.x serialization: maps with enum keys are not supported
    • #198 commitTransactionAndAwait() -> No value received via onNext for awaitSingle
    • #200 getting compilation error on version 4.0.0 (doc update)
    Source code(tar.gz)
    Source code(zip)
  • kmongo-4.0.0(Apr 5, 2020)

    This version is using the 4.0 java driver version and is a breaking changes release. Please consult http://litote.org/kmongo/about/#upgrading-to-4x-from-312x before upgrading.

    Also in this release:

    • #190 Nullable args in documentation
    • #191 .json not translating Pattern correctly
    Source code(tar.gz)
    Source code(zip)
  • kmongo-3.12.2(Mar 6, 2020)

  • kmongo-3.12.1(Feb 28, 2020)

  • kmongo-3.12.0(Jan 23, 2020)

    • #161 add String.from and MongoOperator.from extensions for typed queries
    • #162 generation for id property type not supported
    • #165 typed queries: support of lookup operator
    • Support nullable collection properties by "/"
    Source code(tar.gz)
    Source code(zip)
A basic, incomplete, buggy, far from efficient UI toolkit for Kotlin/Android. An experiment for fun and to learn.

Apex Apex is just a simple proof of concept to demonstrate how easily you can build your own UI Toolkit from scratch. This code base is most likely fu

Romain Guy 79 Sep 7, 2022
A basic, incomplete, buggy, far from efficient UI toolkit for Kotlin/Android. An experiment for fun and to learn.

Apex Apex is just a simple proof of concept to demonstrate how easily you can build your own UI Toolkit from scratch. This code base is most likely fu

Romain Guy 79 Sep 7, 2022
Restful Toolkit for IntelliJ IDEA

restful-toolkit Template ToDo list Create a new IntelliJ Platform Plugin Template project. Get known with the template documentation. Verify the plugi

KeepWalking... 56 Dec 14, 2022
Server & Web App of Tolgee localization toolkit

Server & Web App of Tolgee localization toolkit

Tolgee 534 Jan 8, 2023
Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Kotlin_practice_problems Repo: Programming problems with solutions in Kotlin to help avid Kotlin learners to get a strong hold on Kotlin programming.

Aman 0 Oct 14, 2021
Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP)

Mockative Mocking for Kotlin/Native and Kotlin Multiplatform using the Kotlin Symbol Processing API (KSP). Installation Mockative uses KSP to generate

Mockative 121 Dec 26, 2022
Kotlin-oop - Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto React OOP Repositório criado para ser utilizado pelo projeto de Kotlin OOP desenvolvido em Kotlin nas aulas feitas através da plataforma Alura

Marcos Felipe 1 Jan 5, 2022
Kotlin-koans - Kotlin Koans are a series of exercises to get you familiar with the Kotlin Syntax

kotlin-koans-edu Kotlin Koans are a series of exercises to get you familiar with

null 1 Jan 11, 2022
Kotlin TodoMVC – full-stack Kotlin application demo

Kotlin full stack TodoMVC This project is an example implementation of the TodoMVC app written in Kotlin. More specifically, it's the Kotlin port of t

Gyula Voros 22 Oct 3, 2022
Integration Testing Kotlin Multiplatform Kata for Kotlin Developers. The main goal is to practice integration testing using Ktor and Ktor Client Mock

This kata is a Kotlin multiplatform version of the kata KataTODOApiClientKotlin of Karumi. We are here to practice integration testing using HTTP stub

Jorge Sánchez Fernández 29 Oct 3, 2022
Small kotlin library for persisting _single instances_ of kotlin data classes

PerSista Small library for persisting single instances of kotlin data classes. NB: PerSista uses typeOf() internally which is marked as @ExperimentalS

Eric Donovan 5 Nov 13, 2022
Kotlin Leaning Notes from Udacity Course | Kotlin Bootcamp for Programmers by Google

Kotlin Beginners Notes These are all personal notes taken from the Udacity Course (ud9011) of Kotlin Bootcamp for Programmers by Google as well as oth

Süha Tanrıverdi 34 Dec 10, 2022
Saga pattern implementation in Kotlin build in top of Kotlin's Coroutines.

Module Saga Website can be found here Add in build.gradle.kts repositories { mavenCentral() } dependencies { implementation("io.github.nomisr

Simon Vergauwen 50 Dec 30, 2022
Kotlin microservices with REST, and gRPC using BFF pattern. This repository contains backend services. Everything is dockerized and ready to "Go" actually "Kotlin" :-)

Microservices Kotlin gRPC Deployed in EC2, Check it out! This repo contains microservices written in Kotlin with BFF pattern for performing CRUD opera

Oguzhan 18 Apr 21, 2022
A sample skeleton backend app built using Spring Boot kotlin, Expedia Kotlin Graphql, Reactive Web that can be deployed to Google App Engine Flexible environmennt

spring-kotlin-gql-gae This is a sample skeleton of a backend app that was built using: Spring Boot(Kotlin) Reactive Web Sprinng Data R2DBC with MYSQL

Dario Mungoi 7 Sep 17, 2022
Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin Gradle DSL.

SampleCompose Modular Android architecture which showcase Kotlin, MVVM, Navigation, Hilt, Coroutines, Jetpack compose, Retrofit, Unit test and Kotlin

Mohammadali Rezaei 7 Nov 28, 2022
Learn-kotlin - Learning more about Kotlin in various content

Kotlin study roadmap https://kotlinlang.org/docs/reference/ Getting Started Basi

Danilo Silva 0 Jan 7, 2022
Mis experimentos con Kotlin para JetBrains Academy, certificación de Kotlin donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema.

Kotlin Academy Mis experimentos con Kotlin para JetBrains donde voy resolviendo proyectos de evaluación y haciendo actividades de cada tema. Acerca de

José Luis González Sánchez 1 Jan 10, 2022
Repositório criado para ser utilizado pelo projeto de Kotlin Collections desenvolvido em Kotlin nas aulas feitas através da plataforma Alura.

Projeto Kotlin Collections Repositório criado para ser utilizado pelo projeto de Kotlin Collections desenvolvido em Kotlin nas aulas feitas através da

Marcos Felipe 1 Jan 17, 2022