此查询生成一个具有键/值的对象,符合我的期望
db.empdetails.aggregate( [ { $project: { reportInformationMap: { valu1: 1 } } } ] );
所以在春季数据中我这样做:
Aggregation.project("reportInformationMap.valu1")
Spring数据生成类似这样的内容:
{ "aggregate" : "__collection__" , "pipeline" : [ { "$project" : { "valu1" : "$reportInformationMap.valu1"}}
它起作用,但gimme valu1
作为根值。我需要它作为reportInformationMap
的嵌套值。
您必须为此使用ProjectionOperation.ProjectionOperationBuilder.nested
方法(nested
定义该字段的嵌套字段绑定:]
这里是带有以下输入文档的示例:
{ "name" : { "first" : "John", "last" : "Doe" } }
代码:
ProjectionOperation projection = Aggregation.project().and("name").nested(Fields.fields("name.first"))
Aggregation agg = newAggregation(projection);
AggregationResults<Document> results = mongoTemplate.aggregate(agg, "test", Document.class);
results.forEach(doc -> System.out.println(doc.toJson()));
输出(预计):
{ "name": {"first": "John"} }