Reputation: 23
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
Reputation: 13103
You need to use MongoDB aggregation framework.
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
]
}
]
}
}
}
}
}
}
])
Upvotes: 1