Вложенный поиск в запросе mongo db - PullRequest
0 голосов
/ 30 октября 2019

Я создаю фиктивную веб-страницу авиакомпании, и мне нужно получить все проданные билеты на рейс для всех авиакомпаний, у меня есть 3 коллекции: авиакомпании, рейсы и продажи

Я пытался использовать вложенные поиски в запросе mongodb,но я не могу суммировать общее количество билетов, вот текущий запрос и результат:

Airline.aggregate([{
  $lookup: {
    from: "flights",
    localField: "id_airline",
    foreignField: "id_airline",
    as: "flights"
  }
}, {
  $unwind: {
    path: "$flights",
    preserveNullAndEmptyArrays: true
  }
}, {
  $lookup: {
    from: "sales",
    localField: "flights.id_flight",
    foreignField: "id_flight",
    as: "flights.sales",
  }
}, {
  $group: {
    _id : "$_id",
    idAirline: { $first: "$id_airline" },
    flights: { $push: "$flights" }
  }
}, {
  $project: {
    _id: 1,
    idAirline: 1,
    "flights.id_flight": 1,
    "flights.price": 1,
    "flights.sold":{$sum:"$flights.sales.tickets"}
  }
}]

И результат:

... },
    {
        "_id": "5db381cb18518043c40e3ecd",
        "idAirline": "AVI-242",
        "flights": [
            {
                "id_flight": "CPA-001",
                "price": "125",
                "sold": 0
            },
            {
                "id_flight": "CGA-002",
                "price": "150",
                "sold": 0
            },
            {
                "id_flight": "CHA-003",
                "price": "135",
                "sold": 0
            }
        ]
    },
....

На самом деле, у CPA-001 есть 6 проданных билетовно я не могу подвести итог, чтобы получить результат.

Вот документы:

Авиакомпании

{"_id":{"$oid":"5db3823718518043c40e3ece"},"country":["Panamá","El Salvador","Belice"],"id_airline":"VOL-643","name_airport":"Juan Santamaría","name_airline":"Volaris","createdAt":{"$date":{"$numberLong":"1572045367094"}},"updatedAt":{"$date":{"$numberLong":"1572045367094"}},"__v":{"$numberInt":"0"}}

Полеты

{"_id":{"$oid":"5db9a225154a1b1b08cc77c3"},"restrictions":["No Liquids"],"features":[],"id_flight":"CPA-001","id_airline":"AVI-242","date_departure":{"$date":{"$numberLong":"1546300800000"}},"date_arrival":{"$date":{"$numberLong":"1559779200000"}},"name":"CosPan","origin":"Costa Rica","destination":"Panamá","itinerary":"50 breakfasts","price":"125","status":"On Time","max_capacity":"50","createdAt":{"$date":{"$numberLong":"1572446757327"}},"updatedAt":{"$date":{"$numberLong":"1572447464367"}},"__v":{"$numberInt":"0"}}

Продажи

{"_id":{"$oid":"5db9b643b50c0d1540b8db89"},"id_user":"304780391","id_flight":"CPA-001","origin":"Costa Rica","destination":"Panamá","date_departure":{"$date":{"$numberLong":"1546300800000"}},"date_arrival":{"$date":{"$numberLong":"1559779200000"}},"tickets":{"$numberInt":"4"},"suitcases":{"$numberInt":"1"},"status":"Bought","seat":{"$numberInt":"-1"},"createdAt":{"$date":{"$numberLong":"1572451907375"}},"updatedAt":{"$date":{"$numberLong":"1572451907375"}},"__v":{"$numberInt":"0"}}

1 Ответ

0 голосов
/ 31 октября 2019

Я думаю, что вложенные массивы вызывают некоторые трудности. Я добавил еще один $ unwind между $ lookup и $ group. Дайте мне знать, что вы думаете ...

db.airlines.aggregate([
  { $lookup: {
      from: "flights",
      localField: "id_airline",
      foreignField: "id_airline",
      as: "flights"
    }
  },
  { $unwind: {
      path: "$flights",
      preserveNullAndEmptyArrays: true
    }
  },
  { $lookup: {
      from: "sales",
      localField: "flights.id_flight",
      foreignField: "id_flight",
      as: "flights.sales",
    }
  },
  { $unwind: {
      path: "$flights.sales",
      preserveNullAndEmptyArrays: true
    }
  },
  { $group: {
      _id : "$_id",
      idAirline: { $first: "$id_airline" },
      flights: { $push: "$flights" }
    }
  },
  { $project: {
      _id: 1,
      idAirline: 1,
      "flights.id_flight": 1,
      "flights.price": 1,
      "flights.sold":{$sum: "$flights.sales.tickets"}
    }
  }
]).pretty()

Документы, использованные для проверки:

полеты

{
    "_id" : ObjectId("5db9a225154a1b1b08cc77c3"),
    "restrictions" : [
        "No Liquids"
    ],
    "features" : [ ],
    "id_flight" : "CPA-001",
    "id_airline" : "VOL-643",
    "date_departure" : ISODate("2019-10-30T23:04:17.119Z"),
    "date_arrival" : ISODate("2019-10-30T23:04:17.119Z"),
    "name" : "CosPan",
    "origin" : "Costa Rica",
    "destination" : "Panamá",
    "itinerary" : "50 breakfasts",
    "price" : "125",
    "status" : "On Time",
    "max_capacity" : "50",
    "createdAt" : ISODate("2019-10-30T23:04:17.119Z"),
    "updatedAt" : ISODate("2019-10-30T23:04:17.119Z"),
    "__v" : {
        "$numberInt" : "0"
    }
}

авиакомпании

{
    "_id" : ObjectId("5db3823718518043c40e3ece"),
    "country" : [
        "Panamá",
        "El Salvador",
        "Belice"
    ],
    "id_airline" : "VOL-643",
    "name_airport" : "Juan Santamaría",
    "name_airline" : "Volaris",
    "createdAt" : ISODate("2019-10-30T23:04:17.119Z"),
    "updatedAt" : ISODate("2019-10-30T23:04:17.119Z"),
    "__v" : {
        "$numberInt" : "0"
    }
}

продажи

[{
    "_id" : ObjectId("5db9b643b50c0d1540b8db89"),
    "id_user" : "304780391",
    "id_flight" : "CPA-001",
    "origin" : "Costa Rica",
    "destination" : "Panamá",
    "date_departure" : ISODate("2019-10-30T23:04:17.119Z"),
    "date_arrival" : ISODate("2019-10-30T23:04:17.119Z"),
    "tickets" : 4,
    "suitcases" : {
        "$numberInt" : "1"
    },
    "status" : "Bought",
    "seat" : -1,
    "createdAt" : ISODate("2019-10-30T23:04:17.119Z"),
    "updatedAt" : ISODate("2019-10-30T23:04:17.119Z"),
    "__v" : {
        "$numberInt" : "0"
    }
},
{
    "_id" : ObjectId("5db9b643b50c0d1540b8db8a"),
    "id_user" : "304780391",
    "id_flight" : "CPA-001",
    "origin" : "Costa Rica",
    "destination" : "Panamá",
    "date_departure" : ISODate("2019-10-30T23:04:17.119Z"),
    "date_arrival" : ISODate("2019-10-30T23:04:17.119Z"),
    "tickets" : 4,
    "suitcases" : {
        "$numberInt" : "1"
    },
    "status" : "Bought",
    "seat" : -1,
    "createdAt" : ISODate("2019-10-30T23:04:17.119Z"),
    "updatedAt" : ISODate("2019-10-30T23:04:17.119Z"),
    "__v" : {
        "$numberInt" : "0"
    }
}]
...