首页 > 解决方案 > 如何在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"
}

标签: mongodb

解决方案


您需要将聚合函数与 $lookup 一起使用。

.aggregate([
        {
            $lookup: {
               from: "transationHistory",
               localField: "userId",
               foreignField: "userId",
               as: "result"
            }
        }, //other parts of aggregate
    //match, project, group or whatever you need 
])

推荐阅读