0

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 }} 
])
asked Apr 9, 2022 at 4:16

1 Answer 1

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}
])
answered Apr 13, 2022 at 3:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.