java - 如何在 Java Mongo 投影操作中给出 $toObjectId
问题描述
我是 mongo 的新手。下面是我在mongodb
shell 中进行的聚合操作。但是在我的 java ProjectionAggregation 中,我无法给出$toObjectId
. 请纠正我我错过了什么。
db shell query
db.getCollection('UserData').aggregate([
{
$project : {
"username" : "$username",
"beneficiaries" : "$beneficiaries"
}
},
{
$unwind : {
path : "$beneficiaries",
preserveNullAndEmptyArrays: true
}
},
{
$project : {
"username" : "$username",
"beneficiaries" : "$beneficiaries",
---- dont know how to give $toObjectId in java ProjectionOperation .
"beneficiaryStudId" : { $toObjectId : "$beneficiaries.studentId" }
}
},
{
$lookup:
{
from: "StudentProfileData",
localField: "beneficiaryStudId",
foreignField: "_id",
as: "studProfile"
}
}
])
Java code Projection Operation
ProjectionOperation projectUserAndBeneficiaries = Aggregation.project()
.andExpression("username").as("username")
.andExpression("beneficiaries").as("beneficiaries");
ProjectionOperation projectUserAndOtherDetails = Aggregation.project()
.andExpression("username").as("username")
.andExpression("beneficiaries").as("beneficiaries")
---- How to give $toObjectId in projection operation .andExpression("beneficiaries.studentId").as("beneficiaryStudId");
LookupOperation lookupOperation = LookupOperation.newLookup().
from("StudentProfileData").
localField("beneficiaryStudId").
foreignField("_id").
as("studProfile");
Aggregation agg = Aggregation.newAggregation(projectUserAndBeneficiaries, unwindBeneficiars,
projectUserAndOtherDetails
,lookupOperation);
AggregationResults<UserAndStudentData> output
= mongotemplate.aggregate(agg, "UserData", UserAndStudentData.class);
样本输出
Output in db shell
{
"_id" : ObjectId("5d2f08574de2690001c281ac"),
"username" : "ks241@goo.com",
"beneficiaries" : {
"studentId" : "5d2f0e9c3bcf3e0001a7e562",
"mcBeneficiaryId" : "597418",
"enabled" : true
},
"beneficiaryStudId" : ObjectId("5d2f0e9c3bcf3e0001a7e562"),
"studProfile" : [
{
"_id" : ObjectId("5d2f0e9c3bcf3e0001a7e562"),
"lastName" : "Sharma",
"firstName" : "Kapil",
"studentRegisterCustomFieldValues" : [
{
"bcfdValue" : "One",
"bcfdName" : "Year"
}
],
"gender" : "M",
"merchantId" : "38788943"
}
]
}
在java中
如果我在上面的 java 聚合投影查询中添加 $toObjectId 并运行它会产生与 db shell 相同的值,则 studProfile 数组始终为空。
解决方案
Spring 数据不支持少数类型的方法。这个问题可能包含在其中。但是我们可以使用这个解决方案。
Aggregation aggregation=newAggregation(
p-> new Document("$project",
new Document()
.append("username","$username"),
.append("beneficiaries","$beneficiaries)
.append("beneficiaryStudId",
new Document("$toObjectId","$beneficiaries.studentId")
)
)
)
推荐阅读
- node.js - 从 JSON 模块加载 Nest.js 应用程序的端口号
- typeahead - 不能在另一个函数中调用 typeahead
- reactjs - 路由中带有额外斜杠的 URL 不适用于 react-router
- opendaylight - 如何配置 bgp-ls 对等体
- swift - “任何”类型的值没有成员“valueForKeyPath”
- javascript - 如何从使用 clone() 复制的内容中删除类名
- html - 验证正数和无效日期 ANGULAR FORM
- javascript - 无法使用 express js 发布到嵌套数组
- c++ - 与 unique_ptr 配对的正确方法是什么?
- r - 使用数据子集时如何在 data.table 中创建新列并计算中位数