Quarkus Panache MongoDb 查询,其中查询参数是一个列表

Quarkus Panache MongoDb Query where query parameters are a list

我正在使用 panache 查询 MongoDb,当创建查询文档时,参数在一个列表中。

平时搜索字段unit

时会这样查询
PanacheQuery<BasicInfo> basicInfoPanacheQuery;
Document document = new Document();

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

但是现在我得到 unit 作为 list/array 如下所示,

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

如何搜索单元,即使它们共享相同的键但值是列表或数组。

我终于知道怎么做了

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

要查询某个字段是否在列表中,您可以通过两种方式进行:使用 $or$in

MongoDB 使用 Panache 允许使用文档、原始 JSON 查询或 PanacheQL 进行查询,这是一种接近 JPA 查询语言的指定查询语言。

所有这些形式应该是等价的(未经测试),您可以使用您认为最简单的形式:

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