简体   繁体   English

Spring Data MongoDB-带有嵌套字段投影的聚合

[英]Spring Data MongoDB - aggregate with nested field projection

How can I translate the following into a spring data java query? 如何将以下内容转换为Spring Data 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]}}}
    ])

Messages: 讯息:

{
  "_id": "1",
  "text": "hi",
  "imageId": "1"
}

Images: 图片:

{
  "_id": "1",
  "likers": ["1","2","3"]
}

You can try below aggregation in 3.4 mongo version with 1.10.3 Spring Mongo Version / 1.5.3 Spring Boot Version. 您可以在3.4 mongo版本和1.10.3 Spring Mongo版本/ 1.5.3 Spring Boot版本中尝试以下聚合。

Shell Query for Reference 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 Code: 春季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")
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM