GObirD
GObirD

Reputation: 23

Aggregate array with order in mongodb

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

Upvotes: 2

Views: 48

Answers (1)

Valijon
Valijon

Reputation: 13103

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

Upvotes: 1

Related Questions