Transform field in document's array

Viewed 34

I'm trying to convert some fields from string to integer with aggregate pipelines in MongoDB.

These fields are nested in a document's array, so that they are handled as array too.

Below an example document:

{
    "_id": *****,
    "subject": "first",
    "items": [
        "item_id": "1",
        "ratings": {
            "count": 90,
            "value": "8",
        },
        "item_id": "2",
        "ratings": {
            "count": 75,
            "value": "9",
        },
    ]
}

I tried with $convert and $map (on items.item_id and items.rating.value) but I got the following results:

  • $convert: cannot convert array to int
  • $map: each field becomes an array itself holding values from all items:
{
    "subject": "first",
    "items": [
        "item_id": [1, 2],
        "ratings": {
            "count": 90,
            "value": [8, 9],
        },
        "item_id": [1, 2],
        "ratings": {
            "count": 75,
            "value": [8, 9],
        },
    ]
}

Any help is appreciated :)

1 Answers
  • $map to iterate loop of items array,
  • $toInt to convert value to integer type
  • $mergeObjects to merge current object with modified fields value
db.collection.aggregate([
  {
    $addFields: {
      items: {
        $map: {
          input: "$items",
          in: {
            $mergeObjects: [
              "$$this",
              {
                "ratings": {
                  count: "$$this.ratings.count",
                  value: { $toInt: "$$this.ratings.value" }
                }
              }
            ]
          }
        }
      }
    }
  }
])

Playground

Related