如何在Java Mongo投影操作中给出$toObjectId
我是蒙哥的新蜜蜂。下面是我在如何在Java Mongo投影操作中给出$toObjectId,java,mongodb,aggregation-framework,Java,Mongodb,Aggregation Framework,我是蒙哥的新蜜蜂。下面是我在mongodbshell中执行的聚合操作。但是在我的java ProjectionAggregation中,我无法给出$toObjectId。请纠正我遗漏了什么 db shell查询 db.getCollection('UserData').aggregate([ { $project : { "username" : "$username", "beneficiaries" : &
mongodb
shell中执行的聚合操作。但是在我的java ProjectionAggregation中,我无法给出$toObjectId
。请纠正我遗漏了什么
db shell查询
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代码投影操作
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);
其中如java
如果我在上面的java聚合投影查询中添加$toObjectId并运行它,则studProfile数组始终为空。它生成的值与db shell的值相同。Spring数据不支持几种类型的方法。这个问题可能包括在内。但是我们可以使用这个解决方案
Aggregation aggregation=newAggregation(
p-> new Document("$project",
new Document()
.append("username","$username"),
.append("beneficiaries","$beneficiaries)
.append("beneficiaryStudId",
new Document("$toObjectId","$beneficiaries.studentId")
)
)
)
对不起,如果我在工作,你能纠正我吗。您希望在问题中添加预期的输出@明斯基不懂java,但它从atlas导出到这个
Arrays.asList(project(computed(“username”)、“$username”)、computed(“受益人”、“受益人”)、computed(“受益人研究”、eq(“toObjectId”)、“$受益人.studentId”))
Aggregation aggregation=newAggregation(
p-> new Document("$project",
new Document()
.append("username","$username"),
.append("beneficiaries","$beneficiaries)
.append("beneficiaryStudId",
new Document("$toObjectId","$beneficiaries.studentId")
)
)
)