0

I'm new in mongodb and spring, i need to convert the following query to java code but i didn't find how to do it.

db.collection.aggregate([
{
  $project: {
    members: {
      $concatArrays: [
        [
          {
            "userID": "$userID",
            "userType": "$userType"
          }
        ],
        {
          $reduce: {
            input: "$clients",
            initialValue: [],
            in: {
              $concatArrays: [
                "$$value",
                [
                  {
                    userID: "$$this.userID",
                    userType: "$$this.userType"
                  }
                ],
                "$$this.members"
              ]
            }
          }
        }
      ]
    }
  }
},
{
  $unwind: "$members"
},
{
  $replaceRoot: {
    newRoot: "$members"
  }
}
])

I m stack in the $project part, i didn't find how to implement it in spring. Can someone help me?

1 Answer 1

1

For use cases, where you find it hard to write a query in spring MongoDB java format, You can use the JSON/JavaScript code directly like this:

String jsonExpression = "{\"members\":{\"$concatArrays\":[[{\"userID\":\"$userID\",\"userType\":\"$userType\"}],{\"$reduce\":{\"input\":\"$clients\",\"initialValue\":[],\"in\":{\"$concatArrays\":[\"$$value\",[{\"userID\":\"$$this.userID\",\"userType\":\"$$this.userType\"}],\"$$this.members\"]}}}]}}";
AggregationOperation project = Aggregation.project().and(context -> context.getMappedObject(Document.parse(jsonExpression))).as("difference");

You can refer to my other answer here : Difference between "now" and a given date

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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