0

我有以下查询

db.getCollection('transportations').aggregate(
{
     $group: {
        _id: null,
        departure_city_id: { $addToSet: "$departure.city_id" },
        departure_station_id: { $addToSet: "$departure.station_id" }
     }
  }
);

结果是

{
"_id" : null,
"departure_city_id" : [ 
    ObjectId("5a2f5378334c4442ab5a63ea"), 
    ObjectId("59dae1efe408157cc1585fea"), 
    ObjectId("5a5bbfdc35628410f9fdcde9")
],
"departure_station_id" : [ 
    ObjectId("5a2f53d1334c4442ab5a63ee"), 
    ObjectId("5a2f53c5334c4442ab5a63ed"), 
    ObjectId("5a5bc13435628410f9fdcdea")
]
}

现在我想用集合“areas”查找每个department_city_id以获取该区域的“名称”,并使用集合“stations”查找每个department_station_id以获取车站的“名称”

结果可能是这样的

{
"_id" : null,
"departure_city_id" : [ 
    {
        _id: ObjectId("5a2f5378334c4442ab5a63ea"),
        name: "City 1
    }, 
    {
        _id: ObjectId("59dae1efe408157cc1585fea"),
        name: "City 2
    },
    {
        _id: ObjectId("5a5bbfdc35628410f9fdcde9"),
        name: "City 3
    }
],
"departure_station_id" : [ 
    {
        _id: ObjectId("5a2f53d1334c4442ab5a63ee"),
        name: "Station 1
    }, 
    {
        _id: ObjectId("5a2f53c5334c4442ab5a63ed"),
        name: "Station 2
    },
    {
        _id: ObjectId("5a5bc13435628410f9fdcdea"),
        name: "Station 3
    }
]

}

4

1 回答 1

0
The $lookup aggregation pipeline stage NOW works directly with an array (on 3.3.4 version).

See: lookup between local (multiple)array of values and foreign (single) value

问题的答案只是:

db.getCollection('transportations').aggregate(
{
     $group: {
        _id: null,
        departure_city_id: { $addToSet: "$departure.city_id" },
        departure_station_id: { $addToSet: "$departure.station_id" }
     }
},
{
    $lookup: {
        from: "areas",
        localField: "departure_city_id",
        foreignField: "_id",
        as: "departure_city_id"
    }
},
{
    $lookup: {
        from: "stations",
        localField: "departure_station_id",
        foreignField: "_id",
        as: "departure_station_id"
    }
}
)
于 2018-03-11T06:32:43.750 回答