MapReduce for MongoDB on PHP?



我是MongoDB的新手,这是我第一次使用MapReduce。

我有两个集合:具有以下架构的商店和产品

Products
{'_id', 'type': 'first', 'enabled': 1, 'shop': $SHOP_ID  }
{'_id', 'type': 'second', 'enabled': 0, 'shop': $SHOP_ID  }
{'_id', 'type': 'second', 'enabled': 1, 'shop': $SHOP_ID  }

Shops
{'_id', 'name':'L', ... }
{'_id', 'name':'M', ... }

我正在寻找一个类似的 GROUPBY 语句,用于使用 MapReduce 的 MongoDB 来检索名称为"L"的商店,这些商店的产品具有"启用"=> 1

我该怎么做?谢谢。

应该可以在没有Map Reduce操作的情况下检索所需的信息。

您可以首先在"产品"集合中查询与 {'enabled': 1} 匹配的文档,然后从该查询中获取 $SHOP_ID 列表(我想对应于"商店"集合中的_id值),将它们放在一个数组中,并对"商店"集合执行$in查询,并结合对"名称"的查询。

例如,给定两个集合:

> db.products.find()
{ "_id" : 1, "type" : "first", "enabled" : 1, "shop" : 3 }
{ "_id" : 2, "type" : "second", "enabled" : 0, "shop" : 4 }
{ "_id" : 3, "type" : "second", "enabled" : 1, "shop" : 5 }
> db.shops.find()
{ "_id" : 3, "name" : "L" }
{ "_id" : 4, "name" : "L" }
{ "_id" : 5, "name" : "M" }
> 

首先找到所有匹配 {"enabled" : 1} 的文档

> db.products.find({"enabled" : 1})
{ "_id" : 1, "type" : "first", "enabled" : 1, "shop" : 3 }
{ "_id" : 3, "type" : "second", "enabled" : 1, "shop" : 5 }

从上面的查询中,生成一个_ids列表:

> var c = db.products.find({"enabled" : 1})
> shop_ids = []
[ ]
> c.forEach(function(doc){shop_ids.push(doc.shop)})
> shop_ids
[ 3, 5 ]

最后,在商店集合中查询 shop_ids 数组中具有 _id 值且也与 {name:"L"} 匹配的文档。

> db.shops.find({_id:{$in:shop_ids}, name:"L"})
{ "_id" : 3, "name" : "L" }
> 

关于使用 Mongo 执行等效连接操作的类似问题之前已经提出过。 此问题提供了一些链接,这些链接可能会为您提供其他指导:
如何在 Python 中加入 MongoDB 集合?

如果您想尝试使用 Map Reduce,下面是一个链接,该博客文章来自使用增量 Map Reduce 操作合并两个集合中的值的用户。
http://tebros.com/2011/07/using-mongodb-mapreduce-to-join-2-collections/

希望以上内容可以让您从您的收藏中检索所需的信息。

简短的回答:你不能这样做(用一个MapReduce命令)。

长答案:MongoDB中的MapReduce作业只在单个集合上运行,并且不能在该进程中引用其他集合。因此,这里没有类似 SQL 的 JOIN/GROUP BY 行为。新的聚合框架也仅在单个集合上运行。

我提出了一个由两部分组成的解决方案:

  1. 获取所有名称为"L"的商店。

  2. 编写并运行map-reduce命令,该命令将根据此预先计算的商店列表检查每个产品文档。

最新更新