I have a collection with documents like this:
{
"_id": "5f7db1c8e3ec502bf2f2c97c",
"subject": "AA0001",
"metrics": {
"m001": 40.8,
"m0022": 58.8,
.....
"m0101: -5.0,
}
}
All the fields inside "metrics" are numbers. The negative values are wrong. I want to replace any negative value with "NA". But I have two problems:
- The fields with negative values are different for each document.
- The fields inside "metrics" are not always the same. One document can have more "metrics" than other.
¿Any idea?
2
Answers
you can use
$objectToArray
to convert metrics object into an array of key-value pair objects and then$map
it to transform the array in a way if the number is negative it will be replaced with "NA" using a condition operation. After doing the transformation you can convert the array back to an object using$arrayToObject
playground
you can also update the collection to reflect these changes. Since Mongo 4.2 you can write aggregation pipeline inside
update
calls$addFields
and$set
can be used interchangeablyplayground
You can use below code.