mongodb - 如何在mongodb中加入两个集合
问题描述
我有 2 个集合 userInfo 和 transationHistory。userInfo包含userId、registerDate等,transationHistory包含userId、transationId、itemId等。
数据库如下,有1k多条数据:
transationHistory:{
{
transationId:asd123
itemId:A
userId:123
}
userInfo:{
userId:123
registerDate:"06-18-2018"
}
所以我想获得用他们的 registerDate 购买项目 A 的用户。
db.transationHistory.aggregation({$match:{item:"A"}},{$project:{userId:1}})
然后我得到一个userId列表,然后
db.userInfo.aggregation({$match:{userId:{$in:[<listOfUserId>]}}},{$project:{registerDate:1}})
然后我将两个结果集都放入 excel 并使用 vlookup 函数来获取联合。有没有更简单的方法只使用 mongodb 查询来获取联合?
编辑:
我知道如何在 mySQL 中执行此操作,如下所示:
SELECT T.itemId,T.userId,U.registerDate
FROM transationHistory T,userInfo U
WHERE T.userId=U.userId AND T.itemId="A"
样本输出:
{
itemId:A
userId:123
registerDate:"06-18-2018"
}
{
itemId:A
userId:1435
registerDate:"06-16-2018"
}
解决方案
您需要将聚合函数与 $lookup 一起使用。
.aggregate([
{
$lookup: {
from: "transationHistory",
localField: "userId",
foreignField: "userId",
as: "result"
}
}, //other parts of aggregate
//match, project, group or whatever you need
])
推荐阅读
- grep - 我无法让 grep 从文件中找到“configname:.*:”
- jhipster - 为什么我的微服务没有自动添加用户信息?
- python - 如何在 Python 中动态分配变量名?
- javascript - 使用参数链接订阅多个可观察对象
- c++ - wxWidgets 模糊屏幕和文本
- python - Heroku 发布阶段命令未执行
- swift - 我可以在 Swift 中使用 Spark AR 导出吗?“.arexport”
- c++ - 在枚举中设置位标志的最简单方法是什么?
- javascript - 在 HTML5 Canvas 中绘制一致的手绘虚线
- node.js - npm 不安装任何包无法读取 null 的属性“版本”