【发布时间】:2016-10-12 14:41:17
【问题描述】:
不幸的是,我找不到 Mongo 3.2 java 驱动程序的示例,用于查询“(A 或 B 或 C)和(D 或 E 或 F 或 G)”
括号内的参数数量是可变的 - 最多一百。
我找到了“(A && B) || (X && Y)”的示例,但它对我没有帮助。
How to execute queries with both AND and OR clauses in MongoDB with Java
我的代码产生错误:
MongoQueryException:查询失败,错误代码 2 和错误消息“$or/$and/$nor 条目需要是完整对象”
List<Document> docs = new ArrayList<>();
for (Integer ln: input.getLastnames()) {
docs.add(new Document("lastname",ln));
}
Document queryLN = new Document(
"$or", Arrays.asList(docs)
);
docs.clear();
for (Integer fn: input.getFirstnames()) {
docs.add(new Document("firstname",fn));
}
Document queryFN = new Document(
"$or", Arrays.asList(docs)
);
Document query = new Document(
"$and", Arrays.asList(queryFN,queryLN));
List<Document> result = collectionMain.find(query).into(new ArrayList<Document>());
【问题讨论】:
-
在您的情况下,
Arrays.asList(List<Document>)产生List<List<ListDocument>>。在您引用的示例中,它是List<Document>。我会怪罪的。 -
将 Arrays.asList(docs) 更改为 docs 消除了错误,但结果不在(A 或 B)和(C 或 D)附近。 A 或 B 或 C 或 D 的排序。@saurav 的建议是完整的。非常感谢。