MongoDB Java Error: A pipeline stage specification object must contain exactly one field

MongoDB Java Error: A pipeline stage specification object must contain exactly one field

我正在尝试在 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;
    }

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

您的代码中有一个拼写错误,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<>());