Similar function to $map ,but keeps the original array

Hi. I have a data structure where I have a nested array in an object and then more objects nested in each array element. I want to apply an expression to a value in each array element but want the original array with the applied expression to be the output. So a function like $map only gives me the result of the one value that the expression is applied to not the whole array with all the other objects still in their original place. Is there a function that does this?

Hello, @johan_potgieter!

Please, provide:

  • prettified sample of the document with nested arrays
  • prettified desired output of an aggregation

Hi @slava , i am attaching a sample of the document. All i want to do is keep the data exactly the way it is , i just want to remove the integer in the area key so it only says “A”, “C” etc. mongo .
I tried this.
db.test.aggregate([
{
$project: {
teamStats: {
$map: {
input: ‘$teamStats.data’,
as: ‘rtp’,
in: {
$substr: [’$$rtp.area’, 0, 1],
},
},
},
},
},
]);
but then only get this result below.
mongo2 .
Thanks

Ok, so we need to change the state of the documents from this:

db.test1.insertMany([
  {
    teamStats: {
      data: [
        {
          area: 'A1',
          key: 'K1',
        },
        {
          area: 'B1',
          key: 'K2',
        }
      ]
    }
  }
]);

To this:

{
  "_id" : ObjectId("5f05d6902e6a2f6e49fe1fd4"),
  "teamStats" : {
    "data" : [
      {
        "area" : "A",
        "key" : "K1"
      },
      {
        "area" : "B",
        "key" : "K2"
      }
    ]
  }
}

To achieve that, you need to merge the calculated value into current document in the aggregation pipeline. Like this:

db.test1.aggregate([
  {
    $project: {
      'teamStats.data': {
        $map: {
          input: '$teamStats.data',
          in: {
            $let: {
              vars: {
                // calculate new value for area
                newArea: {
                  $substr: ['$$this.area', 0, 1],
                }
              },
              in: {
                // merge calculated property
                // into current object
                $mergeObjects: ['$$this', {
                  area: '$$newArea',
                }]
              }
            }
          }
        }
      }
    }
  }
]);
1 Like

Great thanks for your help. Will reply on the other post shortly.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.