I tried to use an example in the official document of mongodb,
db.students3.updateMany({ },
[
{ $set: { grade: { $switch: {
branches: [
{ case: { $gte: [ "$average", 90 ] }, then: "A" },
{ case: { $gte: [ "$average", 80 ] }, then: "B" },
{ case: { $gte: [ "$average", 70 ] }, then: "C" },
{ case: { $gte: [ "$average", 60 ] }, then: "D" }
],
default: "F"
} } } }
])
Property grade
is defined as Number
type. I got the error, when tried to update all documents in the database students3,
CastError: Cast to Number failed for value "{ '$switch': { branches: [ [Object] ] } }" (type Object) at path "grade"
Could someone explain the error? Thanks.
CodePudding user response:
You have to $trunc
first, then average
field would be created.
{ $set: { average : { $trunc: [ { $avg: "$tests" }, 0 ] }, modified: "$$NOW" } }
complete update
db.collection.update({},
[
{
$set: {
average: { $trunc: [ { $avg: "$tests" }, 0 ] },
modified: "$$NOW"
}
},
{
$set: {
grade: {
$switch: {
branches: [
{ case: { $gte: [ "$average", 90 ] }, then: "A" },
{ case: { $gte: [ "$average", 80 ] }, then: "B" },
{ case: { $gte: [ "$average", 70 ] }, then: "C" },
{ case: { $gte: [ "$average", 60 ] }, then: "D" }
],
default: "F"
}
}
}
}
])