Search code examples
javamongodbquarkusquarkus-panache

Quarkus Panache MongoDb Query where query parameters are a list


I am using panache to query MongoDb, when creating the query document the parameters are in a list.

Ordinarily I would query like this when searching for the field unit

PanacheQuery<BasicInfo> basicInfoPanacheQuery;
Document document = new Document();

document.add("unit", 1);
basicInfoPanacheQuery = BasicInfo.find(document).page(Page.of(page, PAGE_SIZE));

However am now getting unit as a list/array like below,

List<Integer> units = List.of(1,2);

How do I search for units even if they share the same key but values are a list or array.


Solution

  • I figured out how to do this finally

    // use bison filters
    Bson bson = Filters.or(Filters.eq("unit", 1), Filters.eq("unit", 2));
    
    // convert the bson to a Document
    Document bsonDocument = bsonToDocument(searchBson.toBsonDocument(BsonDocument.class,
            MongoClientSettings.getDefaultCodecRegistry()));
    
    // then pass the document to the panache query
    basicInfoPanacheQuery = BasicInfo.find(bsonDocument).page(Page.of(page, PAGE_SIZE));
    
    // converting a son to a document
    public static Document bsonToDocument(BsonDocument bsonDocument) {
        DocumentCodec codec = new DocumentCodec();
        DecoderContext decoderContext = DecoderContext.builder().build();
        return codec.decode(new BsonDocumentReader(bsonDocument), decoderContext);
      }