Nik*_*ros 6 java sql logical-operators mongodb aggregation-framework
在 SQL 中,您可以执行以下操作;
SELECT * FROM CUSTOMERS WHERE ID=43 AND 1=1
Run Code Online (Sandbox Code Playgroud)
如何将布尔表达式(如“1=1”或“4<6”)作为标准提供给 Java 中的 MongoDB 逻辑运算符?
例如,我可以做到;
collection.find("$or",Arrays.asList(new Document("field1",value1),new Document("field2",value2)))
Run Code Online (Sandbox Code Playgroud)
然而,上述标准总是基于已经存在的字段,而我想做的更像是这样(不会编译);
collection.find("$and",Arrays.asList(new Document(1,1),new Document("field2",value2)))
Run Code Online (Sandbox Code Playgroud)
我需要这个的原因是因为我有一个 '$or' 标准列表,但这个列表可能是空的 - 在这种情况下,我根本不想有任何标准。
更新 1
虽然@gil.fernandes 的解决方案非常适合find查询,但它不适用于聚合查询(这也是我需要的);
AggregateIterable aggregationQuery = collection.aggregate(Arrays.asList(
[...]
new Document("$match", new Document("$or", Arrays.asList(new Document("$where","1==1"))))
));
Run Code Online (Sandbox Code Playgroud)
MongoCommandException:命令失败,错误 16395:“$match 聚合表达式中不允许使用 $where”
关于如何在聚合的 $match 运算符中使用“1=1”逻辑的任何想法?
更新 2
我使用 mongo 服务器版本 3.4.7 应用了@Veeram 的第二个解决方案但是,如果我将addFields和match对象包含到我的聚合查询中,我会得到 0 个结果。如果我删除它们,我会得到所有结果。
collection = mongoClient.getDatabase("testDatabase").getCollection("testColletion");
collection.insertOne(new Document("testField","testValue"));
Bson addFields = Aggregates.addFields(new Field<>("cmp", new Document("$or", Arrays.asList(new Document("$eq", Arrays.asList(1, 1))))));
Bson match = Aggregates.match(Filters.eq("cmp", 1));
AggregateIterable aggregationQuery = collection.aggregate(Arrays.asList(
new Document("$match", new Document("testField", "testValue")),
addFields,
match
));
boolean hasDocuments = aggregationQuery.iterator().hasNext()
Run Code Online (Sandbox Code Playgroud)
您可以$expr在 3.6 mongo 服务器版本上。
import static com.mongodb.client.model.Aggregates.addFields;
import static com.mongodb.client.model.Aggregates.match;
import static com.mongodb.client.model.Filters.*;
import static java.util.Arrays.asList;
Run Code Online (Sandbox Code Playgroud)
就像是
Bson match = match(expr(new Document("$or", asList(new Document("$eq", asList(1, 1))))));
AggregateIterable aggregationQuery = collection.aggregate(asList(
[...]
match
));
Run Code Online (Sandbox Code Playgroud)
这应该输出类似的查询
{ "$match" : { "$expr" : { "$or" : [{ "$eq" : [1, 1] }] } } }
Run Code Online (Sandbox Code Playgroud)
对于3.4以下的版本可以使用$addFields和的组合$match来实现类似的查询。
Bson addFields = addFields(new Field<>("cmp", new Document("$or", asList(new Document("$eq", asList(1, 1))))));
Bson match = match(eq("cmp", true));
AggregateIterable aggregationQuery = collection.aggregate(asList(
[...]
addFields,
match
));
Run Code Online (Sandbox Code Playgroud)
这应该输出类似的查询
{ "$addFields" : { "cmp" : { "$or" : [{ "$eq" : [1, 1] }] } } }
{ "$match" : { "cmp" : true } }
Run Code Online (Sandbox Code Playgroud)