聚合多个mongo集合和备选方案

时间:2017-05-13 05:14:15

标签: mongodb mongoose mongodb-query aggregation-framework

我们有三个代表一个类别的集合。当用户想要查看类别中发生的最近交易时,我们需要从这些集合中获取并显示。我在stackoverflow中看到一些问题,提到聚合多个集合是不允许的。那么,有没有其他选择。在此先感谢

1 个答案:

答案 0 :(得分:0)

如果您正在使用这两个集合中的数千条记录,那么最好使用mongoDB中的“lookup”方法。数十亿条记录是不可取的。

链接:https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/

前,

db.table1.aggregate([
// Join with user_info table
{
    $lookup:{
        from: "table2",       // other table name
        localField: "userId",   // name of table1 field
        foreignField: "userId", // name of table2 field
        as: "t1"         // alias for table1
    }
},
// Join with user_role table
{
    $lookup:{
        from: "table3", 
        localField: "userId", 
        foreignField: "userId",
        as: "alias name"
    }
}
]);
相关问题