【发布时间】:2018-07-30 15:31:03
【问题描述】:
如何使用下面的文档示例在 Spring Data MongoDB Aggregation 中投影嵌入的数组元素字段,我试过了:
project("customers.id")project("customers.[].id")project("customers.?.id")project("$customers.id")
但没用。
没有投影的结果文档:
{
"id": "group1",
"name": "Default Identity Management",
"warningThreshold": 900000,
"tariffId": "TR_0001",
"active": false,
"customers": [
{
"id": "1",
"name": "David",
"properties": [
{
"name": "phone",
"value": "678"
}
],
"roles": [
"dev"
]
},
{
"id": "2",
"name": "Peter",
"properties": [
{
"name": "phone",
"value": "770"
}
],
"roles": [
"techsales",
"dev"
]
}
]
}
预期的文件是这样的:
{
"id" : "group1",
"name" : "Group1",
"tariffId" : "TR_0001",
"warningThreshold" : 900000,
"customers" : [
{
"id" : "1",
"name" : "David",
"properties" : [
{
"name" : "phone",
"value" : "678"
}
]
},
{
"id" : "2",
"name" : "Peter",
"properties" : [
{
"name" : "phone",
"value" : "770"
}
]
}
]
}
我想加入customers[].id、customers[].name、customers[].properties。
【问题讨论】:
-
通过
project.andExclude("customers.roles");使用投影。它应该在 3.4 中使用 spring mongo 2.x jar。 -
我在尝试使用
project("id","customers").andExclude("customers.name")时遇到了异常:'Bad projection specification, cannot exclude fields other than '_id' in an inclusion projection -
是的。几件事。需要的版本是 3.4 mongo server verisin 和 2.0 spring mongo jar。您必须使用额外的项目阶段来排除。不能在单个项目中混合和匹配包含和排除。
-
请检查版本。在 mongo shell 上运行 db.version()。
-
对不起。我没有想到嵌套字段的投影在春天不起作用。你可以试试
AggregationOperation project = new AggregationOperation() { @Override public Document toDocument(AggregationOperationContext aggregationOperationContext) { return new Document("$project", new Document("customers.roles", 0)); } };。使用 lambda,您可以减少到AggregationOperation project = aggregationOperationContext -> new Document("$project", new Document("customers.roles", 0));
标签: java spring mongodb spring-data spring-data-mongodb