如何在 MongoDB 中执行 SQL Join 等效操作?
例如,假设您有两个集合(用户和评论),我想提取 pid=444 的所有评论以及每个集合的用户信息。
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}) )以及与每个评论相关的用户信息?
目前,我首先获取符合我的条件的评论,然后找出该结果集中的所有 uid,获取用户对象,并将它们与评论的结果合并。看来我做错了。
从 Mongo 3.2 开始,这个问题的答案大多不再正确。添加到聚合管道的新 $lookup 运算符本质上与左外连接相同:
https://docs.mongodb.org/master/reference/operator/aggregation/lookup/#pipe._S_lookup 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>
}
}
当然是蒙戈not关系数据库,开发人员正在谨慎推荐 $lookup 的特定用例,但至少从 3.2 开始,现在可以使用 MongoDB 进行连接。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)