将ObjectId投影到spring数据mongo中的String



嗨,下面是我的文档"用户">

{
"_id" : ObjectId("5dcab69fc6355e16d8164bd3"),
"username" : "kellen.swift",
"firstName" : "Kellen",
"lastName" : "Swift",
"authorities" : [],
"active" : true,
"_class" : "...User"
}

"评论">

{
"_id" : ObjectId("5dcac8fc75de953b5c3025cb"),
"content" : "Wonderful, thanks for the explanation",
"videoId" : "5dcab83475de951cc80dd2f0",
"userId" : "5dcab69fc6355e16d8164bd3",
"active" : true,
"_class" : "...Comment"
}

我正在使用以下查询撰写UserComments:

db.users.aggregate([
{
"$project": {
"_id": {
"$toString": "$_id"
},
"username": 1,
"firstName": 1,
"lastName": 1,
}
},
{
$lookup: {
from: "comments",
localField: "_id",
foreignField: "userId",
as: "user_comments"
}
},
{
$unwind: "$user_comments"
},
{
$project:{
username: 1,
name: {
$concat: ["$firstName", " ", "$lastName"]
},
content: "$user_comments.content",
videoId: "$user_comments.videoId"
}
}
]);

这给了我一个使用Robo3t的正确结果。

当我试图从spring数据接口执行相同的命令时,我无法获得确切的结果。

以下是我的java代码:

private void getAllUserCommentsForVideo(String userId) {
ProjectionOperation userProjections = Aggregation.project().andInclude("username", "firstName", "lastName");

LookupOperation lookup = Aggregation.lookup(
"comments",
"_id",
"userId",
"userComments"
);
ProjectionOperation userCommentProject = Aggregation.project(
"username"
).andInclude("userComments.content");
Aggregation aggregation = Aggregation.newAggregation(
userProjections,
lookup,
Aggregation.unwind("userComments"),
userCommentProject
);
List<BasicDBObject> users = mongoTemplate.aggregate(aggregation, "users", BasicDBObject.class).getMappedResults();
for (BasicDBObject object : users) {
System.out.println(object.toJson());
}
}

从Query中,我可以看到_id没有正确映射,我是不是做错了什么。

请告诉我成功执行此操作所需的任何修改。

谢谢。

尝试创建自定义聚合操作以将ObjectId正确映射到字符串:

AggregationOperation projectionOperation = context -> {
Document toString = new Document("$toString", "$_id");
Document id = new Document("_id", toString);
Document project = new Document("$project", id);
return project;
};

最新更新