Skip to content

Instantly share code, notes, and snippets.

@Vibhu-Agarwal
Created November 15, 2019 15:09
Show Gist options
  • Save Vibhu-Agarwal/cc638ccac27ef3d879e439ee8cbec818 to your computer and use it in GitHub Desktop.
Save Vibhu-Agarwal/cc638ccac27ef3d879e439ee8cbec818 to your computer and use it in GitHub Desktop.
M121 | Chapter 3 | Lab 3: $lookup stage
db.air_alliances.aggregate([
{
$lookup:
{
"from": "air_routes",
"foreignField": "airline.name",
"localField": "airlines",
"as": "route_docs"
}
},
{
$project:
{
_id: 0,
name: 1,
valid_routes_binary_array:
{
$map:
{
input: "$route_docs",
as: "route",
in:
{
//If either a Boeing 747 or an Airbus A380 --> 1
//Else --> 0
$cond: [{$in: ["$$route.airplane", ["747", "380"]]}, 1, 0]
}
}
}
}
},
{
$project:
{
name: 1,
routes_count: {$sum: "$valid_routes_binary_array"}
}
},
{
$sort:
{
routes_count: -1
}
}
])
db.air_alliances.aggregate([
{
$lookup:
{
"from": "air_routes",
"foreignField": "airline.name",
"localField": "airlines",
"as": "route_docs"
}
},
{
$project:
{
_id: 0,
name: 1,
valid_routes_array:
{
$filter:
{
input: "$route_docs",
as: "route",
cond:
{
$in: ["$$route.airplane", ['747', '380']]
}
}
}
}
},
{
$project:
{
name: 1,
routes_count: {$size: "$valid_routes_array"}
}
},
{
$sort:
{
routes_count: -1
}
}
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment