Я сделал $unwind: '$lines'
дважды, потому что запрос создал вложенный массив. Как этого избежать?
Stop.aggregate([{
$match: {
'stop_id': {
$regex: /^\d{6}$/
}
}
},
{
$lookup: {
from: "stoptimes",
localField: "stop_id",
foreignField: "stop_id",
as: "stoptimes"
}
},
{
$lookup: {
from: "trips",
localField: "stoptimes.trip_id",
foreignField: "trip_id",
as: "trips"
}
},
{
$limit: 10
},
{
$group: {
_id: '$stop_id',
stop_name: {
$first: '$stop_name'
},
stop_lat: {
$first: '$stop_lat'
},
stop_lon: {
$first: '$stop_lon'
},
lines: {
$addToSet: "$trips.route_id"
}
}
},
{
$unwind: '$lines'
},
{
$unwind: '$lines'
},
{
$project: {
_id: 1,
stop_name: 1,
stop_lat: 1,
stop_lon: 1,
lines: {
$strLenCP: "$lines"
}
}
},
{
$group: {
_id: {
stop_id: '$_id',
stop_name: '$stop_name',
stop_lat: '$stop_lat',
stop_lon: '$stop_lon',
line: '$lines'
},
count: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
stop_id: '$_id.stop_id',
stop_name: '$_id.stop_name',
stop_lat: '$_id.stop_lat',
stop_lon: '$_id.stop_lon',
line: '$_id.line'
}
},
{
$group: {
_id: '$stop_id',
stop_name: {
$first: '$stop_name'
},
stop_lat: {
$first: '$stop_lat'
},
stop_lon: {
$first: '$stop_lon'
},
lineNameLengths: {
$addToSet: '$line'
}
}
},
{
$project: {
_id: 0,
stop_id: '$_id',
stop_name: '$stop_name',
stop_lat: '$stop_lat',
stop_lon: '$stop_lon',
type: {
$switch: {
branches: [{
case: {
$gte: [{
$size: "$lineNameLengths"
}, 3]
},
then: "multiple"
},
{
case: {
$and: [{
$eq: [{
$size: "$lineNameLengths"
}, 2]
},
{
$not: [{
$in: [3, '$lineNameLengths']
}]
}
]
},
then: "tram"
},
{
case: {
$and: [{
$eq: [{
$size: "$lineNameLengths"
}, 2]
},
{
$in: [3, '$lineNameLengths']
}
]
},
then: "multiple"
},
{
case: {
$and: [{
$eq: [{
$size: "$lineNameLengths"
}, 1]
},
{
$in: [1, '$lineNameLengths']
}
]
},
then: "tram"
},
{
case: {
$and: [{
$eq: [{
$size: "$lineNameLengths"
}, 1]
},
{
$in: [2, '$lineNameLengths']
}
]
},
then: "tram"
},
{
case: {
$and: [{
$eq: [{
$size: "$lineNameLengths"
}, 1]
},
{
$in: [3, '$lineNameLengths']
}
]
},
then: "bus"
}
],
default: ""
}
}
}
}]);