我有以下
java
代码,用于创建 Bson
过滤器(按预期工作)。
但是,当我尝试将
projection
添加到我的过滤器时,我得到:
'unknown operator: $project' on server
我的代码中存在什么问题?
private Bson createFilter(String name) {
List<Bson> collectionFilters = new ArrayList<>();
if (name != null) {
filters.add(eq("person_name", name));
}
collectionFilters.add(projectCollectionFields());
return and(collectionFilters);
}
private Bson projectCollectionFields() {
return Aggregates.project(new Document()
.append("_id", new Document("$cond", Arrays.asList(
new Document("$ne", Arrays.asList("$_id", null)),
"$_id",
"$$REMOVE"
)))
.append("name", new Document("$cond", Arrays.asList(
new Document("$ne", Arrays.asList("$person_name", null)),
"$person_name",
"$$REMOVE"
)))
.append("date", new Document("$cond", Arrays.asList(
new Document("$ne", Arrays.asList("$date_added", null)),
"$date_added",
"$$REMOVE"
))));
}
在您的 projectCollectionFields() 中,您正在尝试聚合,您必须仅投影您想要的字段,例如
private Bson projectCollectionFields() {
return Projections.fields(
Projections.include("person_name", "date_added"),
Projections.excludeId()
);
}
修复createFilter(),例如:
private Bson createFilter(String name) {
List<Bson> collectionFilters = new ArrayList<>();
if (name != null) {
collectionFilters.add(Filters.eq("person_name", name));
}
return Filters.and(collectionFilters);
}
然后:
Document doc = collection.find(createFilter(name))
.projection(projectCollectionFields())
.first();