0

I am passing a List<String> that are item ids in a request. I need to get only items that ids are in a list. Basically, I send you a list of product ids and MongoDB should return a List<Product>. I thought it would be something built in, but I cannot achieve it.

I have tried something with aggregate, evaluate etc., but I cannot find a way. I thought it could be as simple as:

override suspend fun getProductsById(input: List<String>): List<Product> {
    return productsCollection.aggregate<Product>(
        match(Product::_id in input)
    ).toList()
}

There is no way in my understanding, but I must be wrong as this, I assume, is like a core feature that a simple API should allow. Probably I could just do a 2008 style with looping through a List<String> and just requesting a product one by one with:

productsCollection.findOne(Product::_id eq itemId)

However, I don't think I should run several requests, this seems as a very wrong idea.

Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Kerubyte
  • 27
  • 6

1 Answers1

1

It works with:

productCollection.find(Product::_id `in` ids)

The in keyword is reserved for the for loop.

ouflak
  • 2,458
  • 10
  • 44
  • 49
Hannes
  • 26
  • 1
  • Correct, thank you, I have found out a while ago about exactly that. What was unclear for me is how to use bson filter infix fun and I was using regular in instead of `in`. Thanks anyway! :) https://mongodb.github.io/mongo-java-driver/3.5/javadoc/com/mongodb/client/model/Filters.html#in-java.lang.String-java.lang.Iterable- – Kerubyte Mar 02 '22 at 12:49