首页 > 解决方案 > MongoDB Java 错误:管道阶段规范对象必须只包含一个字段

问题描述

我正在尝试在 java 上获取此 MongoDB 查询的结果。

db.fileTree.aggregate([
    {
        $match: {
            "_id": "6062144bb25e4809548ef246",
        }
    }, 
    {
        $unwind: "$children"
    },
    {
        $match: {
            "children.fileName": "Test1"
        }
    },
    {
        $project: {
            "_id": 0,
            "fileId": "$children.fileId",
            "fileName": "$children.fileName",
            "directory": "$children.directory",
        }
    }
]).pretty()

查询工作得很好,没有数据时它不显示任何内容。但是,从 java 执行的查询会产生以下错误:

com.mongodb.MongoCommandException: Command failed with error 40323 (Location40323): 'A pipeline stage specification object must contain exactly one field.' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "A pipeline stage specification object must contain exactly one field.", "code": 40323, "codeName": "Location40323"}

ChildFile findChildInParent(String parentId, String fileName) {
        BasicDBObject idFilter = new BasicDBObject().append("_id", parentId);
        BasicDBObject matchId = new BasicDBObject().append("$match", idFilter);
        BasicDBObject unwindChildren = new BasicDBObject().append("$unwind", "$children");
        BasicDBObject childNameFilter = new BasicDBObject().append("children.fileName", fileName);
        BasicDBObject matchChildName = new BasicDBObject().append("$match", childNameFilter);
        BasicDBObject projections = new BasicDBObject()
                .append("_id", 0)
                .append("fileId", "$children.fileId")
                .append("fileName", "$children.fileName")
                .append("directory", "$children.directory");

        List<ChildFile> childFiles = fileCollection.aggregate(
                List.of(matchId, unwindChildren, matchChildName, projections),
                ChildFile.class
        ).into(new ArrayList<>());

        return childFiles.size() > 0 ? childFiles.get(0) : null;
    }

我在这里错过了什么吗?非常感谢任何帮助。谢谢 !

标签: mongodbaggregation-frameworkspring-data-mongodbmongo-java-drivermongo-java

解决方案


$您的代码中有错字,您缺少children字段

应该:

BasicDBObject unwindChildren = new BasicDBObject().append("$unwind", "$children")

代替:

BasicDBObject unwindChildren = new BasicDBObject().append("$unwind", "children")

还缺少$poject阶段:

BasicDBObject projections = new BasicDBObject()
        .append("_id", 0)
        .append("fileId", "$children.fileId")
        .append("fileName", "$children.fileName")
        .append("directory", "$children.directory");

BasicDBObject projectionStage = new BasicDBObject().append("$project", projections);

List<ChildFile> childFiles = fileCollection.aggregate(
        List.of(matchId, unwindChildren, matchChildName, projectionStage),
        ChildFile.class
).into(new ArrayList<>());

推荐阅读