Search code examples
mongodbkmongo

How to get items from collection by ids


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.


Solution

  • It works with:

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

    The in keyword is reserved for the for loop.