【发布时间】:2017-05-13 13:31:17
【问题描述】:
我们有三个代表一个类别的集合。当用户想查看某个类别中最近发生的交易时,我们需要从这些集合中获取并显示。我在 stackoverflow 中看到一些问题,提到不允许聚合多个集合。那么,是否有任何替代方案。提前致谢
【问题讨论】:
标签: mongodb mongoose mongodb-query aggregation-framework
我们有三个代表一个类别的集合。当用户想查看某个类别中最近发生的交易时,我们需要从这些集合中获取并显示。我在 stackoverflow 中看到一些问题,提到不允许聚合多个集合。那么,是否有任何替代方案。提前致谢
【问题讨论】:
标签: mongodb mongoose mongodb-query aggregation-framework
如果您要处理来自这两个集合的数千条记录,最好使用 mongoDB 中的“查找”方法。不建议处理数十亿条记录。
链接: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"
}
}
]);
【讨论】: