如何在java mongo投影操作中给出$toobjectid

uhry853o  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(397)

我是蒙哥的新蜜蜂。下面是我正在执行的聚合操作 mongodb 贝壳。但是在我的java项目聚合中,我不能给出 $toObjectId . 请纠正我遗漏了什么。 db shell query ```
db.getCollection('UserData').aggregate([

{
$project : {
"username" : "$username",
"beneficiaries" : "$beneficiaries"

  1. }

},
{
$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");

  1. ProjectionOperation projectUserAndOtherDetails = Aggregation.project()
  2. .andExpression("username").as("username")
  3. .andExpression("beneficiaries").as("beneficiaries")

---- How to give $toObjectId in projection operation .andExpression("beneficiaries.studentId").as("beneficiaryStudId");

  1. LookupOperation lookupOperation = LookupOperation.newLookup().
  2. from("StudentProfileData").
  3. localField("beneficiaryStudId").
  4. foreignField("_id").
  5. as("studProfile");
  6. Aggregation agg = Aggregation.newAggregation(projectUserAndBeneficiaries, unwindBeneficiars,
  7. projectUserAndOtherDetails
  8. ,lookupOperation);
  9. AggregationResults<UserAndStudentData> output
  10. = mongotemplate.aggregate(agg, "UserData", UserAndStudentData.class);
  1. 样本输出

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"
}
]
}

  1. java
  2. 如果我在上面的java聚合投影查询中添加$toobjectid并运行它,studprofile数组总是空的,它生成的值与db shell相同。
qzwqbdag

qzwqbdag1#

spring数据不支持几种类型的方法。这个问题可能包括在内。但我们可以用这个方法。

  1. Aggregation aggregation=newAggregation(
  2. p-> new Document("$project",
  3. new Document()
  4. .append("username","$username"),
  5. .append("beneficiaries","$beneficiaries)
  6. .append("beneficiaryStudId",
  7. new Document("$toObjectId","$beneficiaries.studentId")
  8. )
  9. )
  10. )

相关问题