mongodb - 在 MongoDB 中搜索多个集合

我知道 MongoDB 的理论和不支持连接的事实,我应该尽可能使用嵌入文档或非规范化,但这里是:

我有多个文档,例如:

  • 嵌入郊区的用户,但也有:名字,姓氏
  • 嵌入国家的郊区
  • 嵌入School的Child属于一个User,但也有:first name, last name

例子:

Users:
{ _id: 1, first_name: 'Bill', last_name: 'Gates', suburb: 1 }
{ _id: 2, first_name: 'Steve', last_name: 'Jobs', suburb: 3 }

Suburb:
{ _id: 1, name: 'Suburb A', state: 1 }
{ _id: 2, name: 'Suburb B', state: 1 }
{ _id: 3, name: 'Suburb C', state: 3 }

State:
{ _id: 1, name: 'LA' }
{ _id: 3, name: 'NY' }

Child:
{ _id: 1, _user_id: 1, first_name: 'Little Billy', last_name: 'Gates' }
{ _id: 2, _user_id: 2, first_name: 'Little Stevie', last_name: 'Jobs' }

我需要实现的搜索是:

  • 用户和 child 的名字、姓氏
  • 来自用户的状态

我知道我必须执行多个查询才能完成它,但是如何实现呢?使用 mapReduce 还是聚合?

你能指出一个解决方案吗?

我尝试使用 mapReduce,但这并没有让我从用户那里获得包含 state_id 的文档,所以这就是我在这里提出它的原因。

最佳答案

This answer is outdated. Since version 3.2, MongoDB has limited support for left outer joins with the $lookup aggregation operator

MongoDB 不执行跨越多个集合的查询 - 周期。当您需要连接来自多个集合的数据时,您必须在应用程序级别通过执行多个查询来完成。

  1. 查询集合 A
  2. 从结果中获取辅助键并将它们放入数组中
  3. 查询集合 B 将该数组作为 $in-operator 的值传递
  4. 在应用层以编程方式加入两个查询的结果

必须这样做应该是异常(exception)而不是常态。当您经常需要模拟这样的 JOIN 时,要么意味着您在设计数据库架构时仍然考虑过于关系化,要么您的数据根本不适合 MongoDB 的基于文档的存储概念。

https://stackoverflow.com/questions/20056903/

相关文章:

mongodb - 你如何告诉 Mongo 在限制结果之前对集合进行排序?

mongodb - 列出mongodb中某个字段的所有值

mongodb - 聚合框架中的 $skip 和 $limit

javascript - 在 Node.js 中进行同步 MongoDB 查询的正确方法是什么?

mongodb - 如何在 MongoDB shell 中中止正在运行的查询?

javascript - MongoDB分页的范围查询

codeigniter - 使用 MongoDB 从数组中删除特定项目

javascript - Mongoose 保存与插入与创建

mongodb - 限制 MongoDB 中的结果但​​仍然获得完整计数?

shell - 为 MongoDB shell 设置默认数据库