mongodb - 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;
}
我在这里错过了什么吗?非常感谢任何帮助。谢谢 !
解决方案
$
您的代码中有错字,您缺少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<>());
推荐阅读
- node.js - 给定一个 ElementHandle,如何找到与之关联的 HTML ID
- django-models - 如果对象的到期日期到了,我如何通过我的 django Web 应用程序发送电子邮件?
- python - AttributeError:模块“tensorflow”没有属性“div”
- pdf - 打开一个大的pdf文件
- automated-tests - 避免 net::ERR_CONNECTION_RESET Protractor JS chromedriver
- python - 如何使用 Selenium 刮取每行的网站 ID
- mysql - 如何使用 GROUP_CONCAT 更新 MySQL 表?
- python - 我的 Postgresql 搜索在后端有效,但在前端无效
- javascript - 如何获取div的html文本
- javascript - 如果数据相同,则推送对象数组