I'm using a lower version of MongoDB so $cond or $switch are giving me the error:
MongoServerError: The dollar ($) prefixed field '$switch' in 'elems.1.val.$switch' is not valid for storage.
I have a collection as below:
{
"attribute": [
{ "type": "ethnicity", "val": "White" },
{ "type": "ethnicity", "val": "Asian" },
{ "type": "Language", "val": "English" }
]
}
I want to update ethnicities to something specific. Example:
Asian --> East Asian,
White --> caucasian
How do I write a query without getting this error?
db.ethnicity.updateMany(
{ "attributes.type": "ethnicity", "attributes.val": { $in: ["asian", "Caucasian"] } },
[
{
$set: {
"attributes.$[elem].val": {
$switch: {
branches: [
{ case: { $eq: [ "asian", "$attributes.$[elem].val" ] }, then: "non-asian" },
{ case: { $eq: [ "Caucasian", "$attributes.$[elem].val" ] }, then: "White" }
],
default: "$attributes.$[elem].val"
}
}
}
}
],
{ arrayFilters: [ { "elem.type": "ethnicity", "elem.val": { $in: ["asian", "Caucasian"] } } ] }
);
Note that according to your sample data and query, the update query won't work as
attributesfield doesn't exist in your attached data. I assume it is a typo error,attributes, instead ofattribute.Meanwhile, the aggregation pipeline can't work together with
arrayFilters.You should use the
$mapoperator to iterate each element in theattributesarray and update each object with thevalfield is only updated if the conditions matched.Demo @ Mongo Playground