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

查看:274
本文介绍了在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:

我有多个文档,例如:

  • 嵌入郊区的用户,但也具有:名字,姓氏
  • 嵌入国家的郊区
  • 嵌入学校的孩子属于一个用户,但还具有:名字,姓氏

示例:

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

我需要执行的搜索位于:

The search I need to implement is on:

  • 用户和孩子的名字,姓氏
  • 用户的状态

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

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

您能指出解决方案吗?

我尝试使用mapReduce,但这并没有让我从包含state_id的Users中获取文档,因此这就是我在此处提出它的原因.

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 聚合运算符

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. 以编程方式在应用程序层上加入两个查询的结果
  1. Query collection A
  2. Get the secondary keys from the result and put them into an array
  3. Query collection B passing that array as the value of the $in-operator
  4. Join the results of both queries programmatically on the application layer

必须这样做,而不是正常情况.当您经常需要模仿这样的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天全站免登陆