Spring 数据 Mongo - 执行不同,但不想在结果中提取嵌入文档
Spring Data Mongo - Perform Distinct, but doesn't wants to pull embedded documents in results
我正在开发 Spring Boot and Spring Data Mongo
示例。在此示例中,我只想获取不同的部门,但不想获取子部门。我需要更改什么查询?
db.employees.distinct("departments");
数据:
{
"firstName" : "Laxmi",
"lastName" : "Dekate",
.....
.......
.....
"departments" : {
"deptCd" : "Tax",
"deptName" : "Tax Handling Dept",
"status" : "A",
"subdepts" : [
{
"subdeptCd" : "1D",
"subdeptName" : "Tax Clearning",
"desc" : "",
"status" : "A"
}
]
},
}
聚合获得不同的 departments.deptCd
值(加上其他详细信息):
db.collection.aggregate( [
{
$group: { _id: "$departments.deptCd",
deptName: { $first: "$departments.deptName" },
status: { $first: "$departments.status" }
}
},
{
$project: { deptCd: "$_id", _id: 0, deptName: 1, status: 1 }
}
] )
输出:
{ "deptName" : "Tax Handling Dept", "status" : "A", "deptCd" : "Tax" }
[编辑添加]
代码使用 Spring 数据 MongoDB v2.2.7:
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "testdb");
Aggregation agg = Aggregation.newAggregation(
Aggregation.group("departments.deptCd")
.first("departments.deptName").as("deptName")
.first("departments.status").as("status"),
Aggregation.project("deptName", "status")
.and("_id").as("deptCd")
.andExclude("_id")
);
AggregationResults<Document> results = mongoOps.aggregate(agg, "collection", Document.class);
results.forEach(System.out::println);
我正在开发 Spring Boot and Spring Data Mongo
示例。在此示例中,我只想获取不同的部门,但不想获取子部门。我需要更改什么查询?
db.employees.distinct("departments");
数据:
{
"firstName" : "Laxmi",
"lastName" : "Dekate",
.....
.......
.....
"departments" : {
"deptCd" : "Tax",
"deptName" : "Tax Handling Dept",
"status" : "A",
"subdepts" : [
{
"subdeptCd" : "1D",
"subdeptName" : "Tax Clearning",
"desc" : "",
"status" : "A"
}
]
},
}
聚合获得不同的 departments.deptCd
值(加上其他详细信息):
db.collection.aggregate( [
{
$group: { _id: "$departments.deptCd",
deptName: { $first: "$departments.deptName" },
status: { $first: "$departments.status" }
}
},
{
$project: { deptCd: "$_id", _id: 0, deptName: 1, status: 1 }
}
] )
输出:
{ "deptName" : "Tax Handling Dept", "status" : "A", "deptCd" : "Tax" }
[编辑添加]
代码使用 Spring 数据 MongoDB v2.2.7:
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "testdb");
Aggregation agg = Aggregation.newAggregation(
Aggregation.group("departments.deptCd")
.first("departments.deptName").as("deptName")
.first("departments.status").as("status"),
Aggregation.project("deptName", "status")
.and("_id").as("deptCd")
.andExclude("_id")
);
AggregationResults<Document> results = mongoOps.aggregate(agg, "collection", Document.class);
results.forEach(System.out::println);