0
votes

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.

2

2 Answers

1
votes

To query that a field is in a list you can do it in two ways: using $or or $in.

MongoDB with Panache allow to query using a Document, a raw JSON query or PanacheQL, a specify query language close to JPA Query Language.

All these forms should be equivalent (not tested), you can use the one that you find the easiest:

// using Document
BasicInfo.find(new Document("$or", new Document("uuid", 1).append("uuid", 2)));
BasicInfo.find(new Document("uuid", new Document("$id", List.of(1, 2))));
// using a raw JSON query
BasicInfo.find("{'$or': {'uuid':1, 'uuid':2}}");
BasicInfo.find("{'uuid': {'$in': [1, 2]}}");
// using Panache QL
BasicInfo.find("uuid in (1,2)");
// or cannot be used in PanacheQL with multiple times the same field name
0
votes

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);
  }