Hi im trying to use a switch statement inside of map to increment a value depending on the case but im getting
MongoServerError: $switch found an unknown argument: $$favcast
is this viable?
db.movies.aggregate([
{$match: {cast: { $elemMatch: { $exists: true } }}},
{$match:{ "tomatoes.viewer.rating": {$gte: 3}}},
{$match:{ countries: {$in: ["USA"]}}},
{$addFields: {num_favs: 0}},
{$project: {
_id: 0,
cast: {
$map: {
input: "$cast",
as: "favcast",
in: { $switch: {
$$favcast:[
{ case: "Sandra Bullock", then: { $add: [ "$num_favs", 1] } },
{ case: "Tom Hanks", then: { $add: [ "$num_favs", 1] } },
{ case: "Julia Roberts", then: { $add: [ "$num_favs", 1] } },
{ case: "Kevin Spacey", then: { $add: [ "$num_favs", 1] } },
{ case: "George Clooney", then: { $add: [ "$num_favs", 1] } },
],
default: { $add: [ "$num_favs", 0 ]}
}
}
}
}
}
},
{$match:{ "num_favs": {$gt: 0}}},
{$project: { num_favs: 1, title: 1 }}
])
1 Answer 1
I didn't end up making the switch work but this did the job for my query. $filter and $reduce
db.movies.aggregate([
{$match: {cast: { $elemMatch: { $exists: true } }}},
{$match:{ countries: {$in: ["USA"]}}},
{$match:{ "tomatoes.viewer.rating": {$gte: 3}}},
{$addFields: {favcast: {$filter:{
input: "$cast",
as: "fave",
cond: {$or: [
{$eq: ["$$fave", "Sandra Bullock"] },
{$eq: ["$$fave", "Tom Hanks"] },
{$eq: ["$$fave", "Julia Roberts"] },
{$eq: ["$$fave", "Kevin Spacey"] },
{$eq: ["$$fave", "George Clooney"] },
]}
} } } },
{$addFields: { num_favs:
{$reduce: {
input: "$favcast",
initialValue: {sum: 0},
in: {
sum: { $add : ["$$value.sum", 1] }
}
}}
}},
{$project: {title: 1, favcast: 1, num_favs: 1, _id: 0 }},
{$sort: { num_favs: -1, "tomatoes.viewer.rating": -1 , title: -1}},
{$skip : 20}
])
lang-sql