如何在mongodb中连接两个集合

如何在mongodb中连接两个集合,mongodb,Mongodb,我有两个集合userInfo和TransactionHistory。userInfo包含userId、registerDate等,TransactionHistory包含userId、TransactionId、itemId等。 数据库如下所示,有超过1k的数据: transationHistory:{ { transationId:asd123 itemId:A userId:123 } userInfo:{ userId:123 registerDate:"

我有两个集合userInfo和TransactionHistory。userInfo包含userId、registerDate等,TransactionHistory包含userId、TransactionId、itemId等。
数据库如下所示,有超过1k的数据:

transationHistory:{
 {
   transationId:asd123
   itemId:A
   userId:123
 }

 userInfo:{
  userId:123
  registerDate:"06-18-2018"
 }
所以我想让那些用注册日期购买商品A的用户

db.transationHistory.aggregation({$match:{item:"A"}},{$project:{userId:1}})  
然后我得到一个userId列表,然后

db.userInfo.aggregation({$match:{userId:{$in:[<listOfUserId>]}}},{$project:{registerDate:1}})
样本输出:

{
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 
])

最后能给我们看一个你想要的数据样本吗?是的。查看聚合框架JFYI的管道,“联合”意味着其他东西。您在这里想要的通常被称为“join”。@SergioTulentsev感谢您的提醒,我是mongodb的新手,英语不是我的第一语言,在这种情况下,“union”是什么意思?@Georgebiley我查看了$lookup,因为这个例子就够了,但是如果我想执行大于或小于的操作,该怎么办?例如,TransactionHistory中的userId小于userInfo中的userId。在页面中,它说“$lookup在foreignField和localField上执行相等匹配”
.aggregate([
        {
            $lookup: {
               from: "transationHistory",
               localField: "userId",
               foreignField: "userId",
               as: "result"
            }
        }, //other parts of aggregate
    //match, project, group or whatever you need 
])