【问题标题】:Mongodb - $group with $addToSet and then $lookupMongodb - $group 与 $addToSet 然后 $lookup
【发布时间】:2018-08-19 07:24:54
【问题描述】:

我有以下查询

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”查找每个离开城市 ID 以获取该区域的“名称”,并使用集合“车站”查找每个离开城市 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
    }
]

}

【问题讨论】:

  • 这个答案的主要区别是我有 2 个不同类型的对象的不同数组。城市和车站。我不能只是放松,因为它会合并它们。

标签: mongodb aggregation-framework mongodb-lookup


【解决方案1】:
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"
    }
}
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-03
    • 2017-03-16
    • 1970-01-01
    • 2013-08-26
    • 2017-10-08
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    相关资源
    最近更新 更多