This is a question inspired by the last optional lab of chapter 1. Spoiler alert if you want to figure out the answer on your own.
var pipeline=[
{
$project:{
"writers":{
$map:{
input: "$writers",
as: "writer",
in:{
$arrayElemAt:[
{ $split : [ "$$writer", " (" ] },
0
]
}
}
},
"cast":{
$map:{
input: "$cast",
as: "castMember",
in:{
$arrayElemAt:[
{ $split : [ "$$castMember", " (" ] },
0
]
}
}
},
"directors":{
$map:{
input: "$directors",
as: "dir",
in:{
$arrayElemAt:[
{ $split : ["$$dir", " ("] },
0
]
}
}
},
"_id" : 0,
"title" : 1
}
},
{
$project:{
"allThree":{
$size: { $setIntersection : ["$directors", "$writers", "$cast"] }
},
"title": 1
}
},
{
$match: { "allThree" : { $gt : 0 } }
}
]
As you can see I have three project stages, each using $map
against an array to perform $split
operation against all items in the array.
What I am wondering is if it’s possible to use $map
against $map
to turn a three stage projection into a one stage projection. Something like…
var pipeline =[
{
$addFields:{
"allThree":{
$map:{
input: ["$directors", "$writers", "$cast"],
as: "array",
in:{
$map:{
input: "$$array",
as: "person",
in:{
$arrayElemAt:[
{ $split : ["$$person", " ("] },
0
]
}
}
}
}
}
}
}
]
I tried that out, and it basically combines writers, directions, and actors into a list of lists. But I can’t figure out what to do from there. I try to use $setIntersection
, but I can’t get $setIntersection
to compare the arrays at the right level.