如何将以下内容翻译成spring数据java查询?
db.messages.aggregate([
{$lookup:{from: "images", localField: "imageId", foreignField: "_id", as: "image"}},
{$unwind: "$image"},
{$project: {"text": 1, "liked": {$gt: [{$size: {$setIntersection: ['$image.likers', ['2']]}}, 0]}}}
])
消息:
{
"_id": "1",
"text": "hi",
"imageId": "1"
}
图片:
{
"_id": "1",
"likers": ["1","2","3"]
}
答案 0 :(得分:1)
您可以在3.4 mongo版本中使用1.10.3 Spring Mongo Version / 1.5.3 Spring Boot Version进行以下聚合。
Shell查询参考
db.messages.aggregate(
{ "$lookup" : { "from" : "images" , "localField" : "imageId" , "foreignField" : "_id" , "as" : "image"}} ,
{ "$unwind" : "$image"} ,
{ "$project" : { "text" : 1 , "liked" : { "$in" : [ "2" , "$image.likers"]}}}
)
Spring Mongo代码:
import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
import static org.springframework.data.mongodb.core.aggregation.ArrayOperators.arrayOf;
Aggregation agg = newAggregation(
lookup("images", "imageId", "_id", "image"),
unwind("image"),
project("text").and(arrayOf("image.likers").containsValue("2")).as("liked")
);