Mongodb query returns null for nested queries (KMongo)

380 views Asked by At

I'm new to ktor and am writing an application using it. I'm trying to add authors and their book titles and retrieve them from the database. My schema is given below. (authors is my collection name)

authors = [
  {
    name: "Author1",
    books: [{ title: "Book1" }, { title: "Book2" }],
  },
];

I'm trying to check whether a book title has already been added under a particular author. So I wrote a findBookitemBytitle function as shown below. My issue is that every time I'm getting a null result. Even though actually data satisfying the query condition is present in it.

My code

I have followed the Kmongo documentation since I am using Kmongo as the driver here. According to their documentation I've written the following code.

data classes

@kotlinx.serialization.Serializable
    data class Author ( val name: String , val books : MutableList<Bookitem>)
    @kotlinx.serialization.Serializable
    data class Bookitem (val title :String)

functions

private var collection : CoroutineCollection<Author> = MongoConfig.getDatabase().getCollection("authors")


suspend fun findBookitemBytitle(Name:String,Title:String) : Author?{
      return collections.findOne(and(Author::name eq Name,Bookitem::title eq Title))          

Any help is appreciated. If any more details are required please do ask.

1

There are 1 answers

0
Anandakrishnan On BEST ANSWER

I solved this by using a '/'.

 return collections.findOne(and(Author::name eq Name,books::Bookitem/Bookitem::title eq Title))