Adding the position of a sub-document in an array as field inside that sub-document

I am working on a json object that has the following structure:

Initial

{overs: [ 
 {over:1,
  deliveries: [{runs:1},{runs:0},{runs:2},{runs:4},{runs:0},{runs:0}]
 },
 {over:2,
  deliveries: [{runs:3},{runs:6},{runs:2},{runs:0},{runs:0},{runs:0}]
 },
 ...]
}

Inside the deliveries array, I want to add a new field ballNo whose value is equal to the position of the sub-document

Required

{overs: [
 {over:1,
  deliveries: [{ballNo:1, runs:1},{ballNo:2, runs:0},{ballNo:3, runs:2},{ballNo:4, runs:4},{ballNo:5, runs:0},{ballNo:6, runs:0}]
 }, 
 {over:2,
  deliveries: [{ballNo:1, runs:3},{ballNo:2, runs:6},{ballNo:3, runs:2},{ballNo:4, runs:0},{ballNo:5, runs:0},{ballNo:6, runs:0}]
 },
 ...]
}

Using aggregation pipeline, I would use:

$range to $addFields an array [ 1 … $size of deliveries ]
$map the $range above with $mergeObject for each element of deliveries

And if what you want needs to be permanent, a $merge stage back in the original collection.

1 Like