Search code examples
mongodbquarkusquarkus-panache

Is there a way to execute a list(List<ObjectId> id) to find documents that match the list?


I'm persisting the data on a MongoDB Database using Panache repository strategy.

@ApplicationScoped
public class ProductRepository implements PanacheMongoRepository<Product> {}

Assume that I have a collection with the following data on it.

|id  | name | price |
|1   | p1   | $ 1.00|
|2   | p2   | $ 2.00|
|3   | p3   | $ 3.00|
|4   | p4   | $ 4.00|

And I have a List<ObjectId> productsToRetrieve with [1, 3]

and the expected result from a query would be:

id name price
1 p1 $ 1.00
3 p3 $ 3.00

Here's what I've tried

find("id", productsToRetrieve);
find("id = ?1", productsToRetrieve);
list("id", productsToRetrieve);
Document query = new Document();
find(new Document("id", new Document("$in", productsId))).list();

I could use a forEach to retrieve each product from the repository and add to a list, but that's not a good approach. A PanacheQL query would solve the problem, but I don't know how to.


Solution

  • To get the desired output is necessary to use $in. Example here.

    And using quarkus, according to docs, it says:

    status in ?1 will be mapped to {'status':{$in: [?1]}}

    So the necessary query is:

    _id in ?1, ?3