在 MongoDB 中搜索多个集合 [英] Search on multiple collections in MongoDB

查看:44
本文介绍了在 MongoDB 中搜索多个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know the theory of MongoDB and the fact that is doesn't support joins, and that I should use embeded documents or denormalize as much as possible, but here goes:

我有多个文件,例如:

  • 用户,嵌入郊区,但也有:名字,姓氏
  • 嵌入州的郊区
  • 嵌入 School 的孩子属于用户,但也有:名字、姓氏

示例:

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' }

我需要实现的搜索是:

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

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

I know that I have to do multiple queries to get it done, but how can that be achieved? With mapReduce or aggregate?

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

Can you point out a solution please?

我曾尝试使用 mapReduce 但这并没有让我从用户那里获得包含 state_id 的文档,所以这就是我把它带到这里的原因.

I've tried to use mapReduce but that didn't get me to have documents from Users which contained a state_id, so that's why I brought it up here.

推荐答案

这个答案已经过时了.从 3.2 版开始,MongoDB 对使用 $lookup 聚合运算符<的左外连接的支持有限/p>

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

MongoDB 不执行跨越多个集合的查询 - 期间.当你需要连接来自多个集合的数据时,你必须在应用层通过多次查询来完成.

MongoDB does not do queries which span multiple collections - period. When you need to join data from multiple collections, you have to do it on the application level by doing multiple queries.

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

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

Having to do this should be rather the exception than the norm. When you frequently need to emulate JOINs like that, it either means that you are still thinking too relational when you design your database schema or that your data is simply not suited for the document-based storage concept of MongoDB.

这篇关于在 MongoDB 中搜索多个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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