我正在研究Spring Boot v.2.1.3.3.RELEASE和Spring Data MongoDB。由于关键的要求,我假设员工知道多种技术,但主要语言将是任何人。
因此,我决定将技术集合与在员工集合中与员工和技术相关的方式分开。
{ "_id" : ObjectId("5ec65750fdcd4e960f4b2f24"), "technologyCd" : "AB", "technologyName" : "My ABC", "ltechnologyNativeName" : "XY", "status" : "A" }
所以,我完成了如下所示的关联-
注意:多个技术可以与一个雇员相关联
一个员工可以与多种技术关联
员工只能拥有一种主要技术
{ "_id" : ObjectId("5ec507c72d8c2136245d35ce"), "firstName" : 442, "lastName" : "LU", "email" : "LUX", ....... ....... ....... "employeeTechnologyRefs" : [ { "technologyCd" : "AB", "primaryTechnologySw" : "Y", "Active" : "A" }, { "technologyCd" : "AB", "primaryTechnologySw" : "N", "Active" : "A" }, { "technologyCd" : "PR", "primaryTechnologySw" : "N", "Active" : "A" }, { "technologyCd" : "PR", "primaryTechnologySw" : "N", "Active" : "A" } ], "countryPhoneCodes" : [ "+352" ], .... ... }
我在下面的查询中使用了,如何查询技术文档以获取结果并将其映射并创建最终对象?
Criteria criteria = new Criteria(); criteria.andOperator( StringUtils.isNotBlank(firstName) ? Criteria.where("firstName").is(firstName.toUpperCase()) : Criteria.where(""), StringUtils.isNotBlank(lastName) ? Criteria.where("lastName").is(lastName.toUpperCase()) : Criteria.where(""), StringUtils.isNotBlank(email) ? Criteria.where("email").is(email.toUpperCase()) : Criteria.where(""), StringUtils.isNotBlank(technologyCd) ? Criteria.where("employeeTechnologyRefs.technologyCd").is(technologyCd.toUpperCase()) : Criteria.where("")); MatchOperation matchStage = Aggregation.match(criteria); GroupOperation groupOp = Aggregation .group("firstName", "lastName", "email","_id") .addToSet("employeeTechnologyRefs").as("employeeTechnologyRefs"); ProjectionOperation projectStage = Aggregation.project("employeeTechnologyRefs"); Aggregation aggregation = Aggregation.newAggregation(matchStage, groupOp, projectStage); AggregationResults<CustomObject> results = mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(Employee.class), CustomObject.class); System.out.println(results);
结果应如下图所示
{
"_id" : ObjectId("5ec507c72d8c2136245d35ce"),
"firstName" : 442,
"lastName" : "LU",
"email" : "LUX",
.......
.......
.......
"employeeTechnologyRefs" : [
{
"technologyCd" : "AB",
"technologyName" : "My ABC",
"ltechnologyNativeName" : "XY",
"primaryTechnologySw" : "Y",
"Active" : "A"
},
{
"technologyCd" : "AB",
"technologyCd" : "AB",
"technologyName" : "My ABC",
"ltechnologyNativeName" : "XY",
"primaryTechnologySw" : "Y",
"Active" : "A"
},
{
"technologyCd" : "PR",
"technologyCd" : "AB",
"technologyName" : "My ABC",
"ltechnologyNativeName" : "XY",
"primaryTechnologySw" : "Y",
"Active" : "A"
},
{
"technologyCd" : "PR",
"technologyCd" : "AB",
"technologyName" : "My ABC",
"ltechnologyNativeName" : "XY",
"primaryTechnologySw" : "Y",
"Active" : "A"
}
],
"countryPhoneCodes" : [
"+352"
],
....
}
我正在使用Spring Boot 2.1.3.3.RELEASE和Spring Data MongoDB。由于关键的要求,我假设员工知道多种技术,但我必须像下面那样建模,但是主要语言是...
如果您在代码中使用以下查找操作,则应该能够按预期方式获得答案,并且您无需在代码中进行分组操作。