【问题标题】:How to add to an existing MongoDB Bson Filter in Java如何在 Java 中添加到现有的 MongoDB Bson 过滤器
【发布时间】:2018-09-27 07:06:02
【问题描述】:

我正在使用 MongoDB 3.6.3 和 Java 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));

我需要有条件地向过滤器添加另一个字段,从而有效地实现:

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

【问题讨论】:

  • 您可以使用 Arraylist。类似List<Bson> fields = new ArrayList<>(); fields.add(eq("field1",value)); fields.add( gt("field2", value2)); if(optionFieldRequired) { fields.add(eq("field3", optionalValue)); } Bson filter = and(fields);

标签: java mongodb mongodb-java bson


【解决方案1】:

Filters.and() 返回私有静态类的实例:Filters.AndFilterAndFilter 上没有公共方法允许您更改其状态。 因此,如果您想在构造此对象后附加一个额外的过滤器,您必须将其转换为其他一些可变的形式。例如; BsonDocument

以下代码创建两个BsonDocument 实例,一个通过向现有过滤器集添加一个过滤器,另一个通过一次创建所有三个过滤器。这两个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, MongoClientSettings.getDefaultCodecRegistry());

assertThat(completeBsonDocument, is(bsonDocument));

所以,这个解决方案是功能性的,但我认为它比将 create 调用包装在条件块中更难理解,也更不标准,就像在你的问题中一样......

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

【讨论】:

  • 谢谢。我认为可能是这种情况,但如果你问的话,你可以得到一些关于 Stack Overflow 的很酷的见解 :-)
  • MongoClient.getDefaultCodecRegistry() 替换为 MongoClientSettings.getDefaultCodecRegistry()
  • 此答案无效,append() 将在之前的$and 子句的同时追加另一个新子句。
猜你喜欢
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
  • 2021-08-26
  • 2023-02-26
  • 2022-01-26
  • 2021-10-08
  • 2017-02-08
  • 1970-01-01
相关资源
最近更新 更多