0

How can I translate the following into a spring data java query?

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"]
}
2
  • Basically I am trying to add a new field called "liked" and it should be true if user X liked the message/image. Commented May 22, 2017 at 11:45
  • Not clear what you want to do. explain in detail Commented May 22, 2017 at 14:49

1 Answer 1

2

You can try below aggregation in 3.4 mongo version with 1.10.3 Spring Mongo Version / 1.5.3 Spring Boot Version.

Shell Query for Reference

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:

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")
);
Sign up to request clarification or add additional context in comments.

3 Comments

What is arrayOf here?
@Sachin arrayOf is a static factory method to get reference to array operator factory and you can then perform operations on array. One such operations is containsValue which renders $in expression`. For complete list visit here
as I mentioned on another question. can we use List of value in containsValue ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.