如何在MongoDB中执行等效的SQL Join? [英] How do I perform the SQL Join equivalent in MongoDB?

查看:91
本文介绍了如何在MongoDB中执行等效的SQL Join?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在MongoDB中执行等效的SQL Join?

How do I perform the SQL Join equivalent in MongoDB?

例如,说您有两个集合(用户和评论),我想提取所有带有pid = 444的评论以及每个用户的用户信息.

For example say you have two collections (users and comments) and I want to pull all the comments with pid=444 along with the user info for each.

comments
  { uid:12345, pid:444, comment="blah" }
  { uid:12345, pid:888, comment="asdf" }
  { uid:99999, pid:444, comment="qwer" }

users
  { uid:12345, name:"john" }
  { uid:99999, name:"mia"  }

是否有一种方法可以一次性提取所有带有特定字段的评论(例如... find({pid:444}))以及与每个评论关联的用户信息?

Is there a way to pull all the comments with a certain field (eg. ...find({pid:444}) ) and the user information associated with each comment in one go?

目前,我首先要获取符合我的条件的注释,然后找出该结果集中的所有uid,获取用户对象,然后将它们与注释结果合并.好像我做错了.

At the moment, I am first getting the comments which match my criteria, then figuring out all the uid's in that result set, getting the user objects, and merging them with the comment's results. Seems like I am doing it wrong.

推荐答案

从Mongo 3.2开始,对该问题的答案大多不再正确.添加到聚合管道中的新$ lookup运算符实质上与左外部联接相同:

As of Mongo 3.2 the answers to this question are mostly no longer correct. The new $lookup operator added to the aggregation pipeline is essentially identical to a left outer join:

https://docs.mongodb.org/master /reference/operator/aggregation/lookup/#pipe._S_lookup

从文档中

{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

当然Mongo不是关系数据库,开发人员正在谨慎地建议$ lookup的特定用例,但至少从3.2版本开始,MongoDB现在可以进行联接.

Of course Mongo is not a relational database, and the devs are being careful to recommend specific use cases for $lookup, but at least as of 3.2 doing join is now possible with MongoDB.

这篇关于如何在MongoDB中执行等效的SQL Join?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆