我正在尝试Spring Boot v.2.1.3.RELEASE 和 Spring Data MongoDB。由于关键要求,我必须像下面这样进行建模,假设员工了解多种技术,但主要语言是任何人。
因此,我决定将技术集合分开,并在员工集合中以某种方式将员工和技术相关联。
{
"_id" : ObjectId("5ec65750fdcd4e960f4b2f24"),
"technologyCd" : "AB",
"technologyName" : "My ABC",
"ltechnologyNativeName" : "XY",
"status" : "A"
}
所以,我做了如下关联 -
注意:一名员工可以关联多种技术
一名员工可以与多种技术相关联
员工只能拥有一项且仅有一项主要技术
{
"_id" : ObjectId("5ec507c72d8c2136245d35ce"),
"firstName" : "John",
"lastName" : "Doe",
"email" : "[email protected]",
.......
.......
.......
"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"
}
],
....
}