-1

我是 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', ... }

我正在为带有 MapReduce 的 MongoDB 寻找 GROUPBY 类似的语句,以检索名称为“L”且产品为“已启用”=> 1 的商店

我该怎么做?谢谢你。

4

2 回答 2

1

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

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

例如,给定两个集合:

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

根据上述查询,生成 _id 列表:

> 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 执行相当于 join 操作的问题。这个问题提供了一些链接,可以为您提供额外的指导:
如何在 Python 中加入 MongoDB 集合?

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

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

于 2012-04-23T22:33:07.677 回答
0

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

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

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

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

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

于 2012-04-18T20:34:06.190 回答