2

This is current result

 {{"id": 1, "result":["a", "b", "c", "d"]},{"id": 2, "result":["e", "f", "g", "h"]}}

What I want is

 {{"id": 1, "result":[{"before": "a", "after": "b"},{"before": "b", "after": "c"},{"before": "c", "after": "d"}]},{"id": 2, "result":[{"before": "e", "after": "f"},{"before": "f", "after": "g"},{"before": "g", "after": ""}]}}

I dont have any idea how to do it T_T

1
  • you have to read it to a JSONParser like Jackson and manipulate your current result to get what you want. Its pretty manual :) Commented Jul 2, 2020 at 12:55

1 Answer 1

1

You need to use MongoDB aggregation framework.

Pseudocode

var tmp = [];
for(var idx=0; idx < result.length-1; idx++){
    tmp.append({before: result[idx], after: result[idx + 1]});
}
root.result = tmp;

db.collection.aggregate([
  {
    $project: {
      id: 1,
      result: {
        $map: {
          input: {
            $range: [
              0,
              {
                $subtract: [
                  {
                    $size: "$result"
                  },
                  1
                ]
              },
              1
            ]
          },
          as: "idx",
          in: {
            before: {
              $arrayElemAt: [
                "$result",
                "$$idx"
              ]
            },
            after: {
              $arrayElemAt: [
                "$result",
                {
                  $add: [
                    "$$idx",
                    1
                  ]
                }
              ]
            }
          }
        }
      }
    }
  }
])

MongoPlayground

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.