簡體   English   中英

Quarkus Panache MongoDb 查詢其中查詢參數是列表

[英]Quarkus Panache MongoDb Query where query parameters are a list

我正在使用 panache 查詢 MongoDb,創建查詢文檔時,參數在列表中。

通常我在搜索字段單元時會這樣查詢

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

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

但是,我現在將單元作為列表/數組,如下所示,

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

即使它們共享相同的鍵但值是列表或數組,我如何搜索單元。

要查詢某個字段是否在列表中,您可以通過兩種方式進行:使用$or$in

帶有 Panache 的 MongoDB 允許使用文檔、原始 JSON 查詢或 PanacheQL(一種接近 JPA 查詢語言的指定查詢語言)進行查詢。

所有這些 forms 應該是等效的(未經測試),您可以使用您認為最簡單的一個:

// 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

我終於想出了如何做到這一點

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM