web-dev-qa-db-ja.com

Javaで既存のMongoDB Bsonフィルターに追加する方法

私はJava用にMongoDB 3.6.3と3.6.0 Mongo&Bsonドライバーを使用しています。

次のフィルターがあるとします。

import static com.mongodb.client.model.Filter.and;
import static com.mongodb.client.model.Filter.eq;
import static com.mongodb.client.model.Filter.gt;
.
.
.
   Bson filter = and(eq("field1", value),
                     gt("field2", value2));

条件付きで別のフィールドをfilterに追加して、効果的に作成する必要があります。

   Bson filter = and(eq("field1", value),
                     gt("field2", value2),
                     eq("field3", optionalValue));

そのフィールドをfilterに追加することでこれを行う方法はありますか、それとも個別にフィルターを作成する必要がありますか?例えば。

   Bson filter;
   if (optionFieldRequired)
   {
      Bson filter = and(eq("field1", value),
                        gt("field2", value2));
   }
   else
   {
      Bson filter = and(eq("field1", value),
                        gt("field2", value2),
                        eq("field3", optionalValue));
   }
5
Spuggiehawk

Filters.and()は、プライベート静的クラスのインスタンスを返します:_Filters.AndFilter_。 AndFilterには、状態を変更できるパブリックメソッドはありません。したがって、このオブジェクトを作成した後に追加のフィルターを追加したい場合は、それを他の変更可能なフォームに変換する必要があります。例えば; BsonDocument

次のコードは、2つのBsonDocumentインスタンスを作成します。1つは既存のフィルターセットにフィルターを追加し、もう1つは3つすべてのフィルターを一度に作成します。これらのBsonDocumentインスタンスはどちらも同じであり、collection.find()で使用できます。

_Bson filter = and(eq("field1", "value"), gt("field2", "value2"));
BsonDocument bsonDocument = filter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());

Bson optionalFilter = eq("field3", "optionalValue");
BsonDocument optionalBsonDocument = optionalFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());

// now add the optional filter to the BsonDocument representation of the original filter
bsonDocument.append("field3", optionalBsonDocument.get("field3"));

Bson completeFilter = and(eq("field1", "value"), gt("field2", "value2"), eq("field3", "optionalValue"));
BsonDocument completeBsonDocument = completeFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());

assertThat(completeBsonDocument, is(bsonDocument));
_

したがって、このソリューションは機能的ですが、質問のように、条件付きブロックでcreate呼び出しをラップするよりも理解が難しく、標準的ではないと思います...

_Bson filter;
if (optionFieldRequired) {
  Bson filter = and(eq("field1", value),
                    gt("field2", value2));
} else {
  Bson filter = and(eq("field1", value),
                    gt("field2", value2),
                    eq("field3", optionalValue));
}
_
1
glytching