Convert a JSON field to JSON string

Hello, I am currently trying to export a collection to S3 with a Trigger function.
I would like to know if it’s possible to create a string from an object (dictionary) field.

Example of document:

{
   "_id": 1,
   "data": {
      "key1": "value1",
      "key2": "value2"
   },
   "updatedAt": "2022-08-16T09:00:09.681+00:00"
}

Example of output

{
   "_id": 1,
   "data": "{\"key1\": \"value1\", \"key2\": \"value2\"}",
   "updatedAt": "2022-08-16T09:00:09.681+00:00"
}

This is some sample of code I tried (JSON.stringify($data) is not working)

exports = function () {
   const pipeline = [
      {
        $match: {
           "updatedAt": {
              $gt: new Date(Date.now() - 300 * 1000),
              $lt: new Date(Date.now())
           }
        }
      },
      {
        $addFields: {
          "test": {
            $cond: {
              if: {
                $eq: [{$type: "$data"}, 'object']
              },
              then: JSON.stringify($data),
              else: "$data"
            }
          }
        }
      },
      {
        $project: {
          "_id": 1, 
          "test": 1
        }
      }, {
        "$out": {
           "s3": {
              "bucket": "bucket",
              "region": "region",
              "filename":"filename",
              "format": {
                    "name": "parquet",
                    "maxFileSize": "10GB",
                    "maxRowGroupSize": "100MB"             
            }
          }
        }
      }
   ];
   return events.aggregate(pipeline);
};  

You can’t use a JS function inside $addFields because it expects aggregation expressions (you should be able to do it using $function though running JS inside the server is usually inefficient).

Asya

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