MongoDB 驱动程序 Java:服务器上的“未知操作员:$project”

问题描述 投票:0回答:1

我有以下

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"
                ))));
    }
java mongodb nosql projection bson
1个回答
0
投票

在您的 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();
© www.soinside.com 2019 - 2024. All rights reserved.