【问题标题】:MapReduce for MongoDB on PHP?在 PHP 上用于 MongoDB 的 MapReduce?
【发布时间】:2012-04-18 20:30:30
【问题描述】:

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

我有两个集合:具有以下架构的 Shops 和 Products

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 的商店

我该怎么做?谢谢。

【问题讨论】:

  • 您是否需要经常将这些收藏夹在一起?如果是这样,您可能需要重新考虑使用 MongoDb 或重新考虑您的架构。
  • 您好,您有什么运气吗? Marc 的回答看起来相当不错,我认为应该得到某种反馈。
  • 实际上我们转移到了一个对 sql 友好的数据库。 Mongo 适合其他操作
  • 好的。在这种情况下,请考虑对以下每个答案进行投票 - 您得到了两个人的善意帮助,但都没有时间回复。

标签: php mongodb mapreduce


【解决方案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 }

从上面的查询中,生成一个_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 执行相当于连接操作的类似问题。这个问题提供了一些链接,可以为您提供额外的指导:
How to join MongoDB collections in Python?

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

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

【讨论】:

    【解决方案2】:

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

    长答案:MongoDB 中的 MapReduce 作业仅在单个集合上运行,不能引用进程中的其他集合。所以,JOIN/GROUP BY-like SQL 的行为在这里不可用。新的聚合框架也仅在单个集合上运行。

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

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

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

    【讨论】:

    • 您能帮我使用 MapReduce 命令吗?我读了一点,但我不知道如何在这里应用它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    • 2015-09-27
    相关资源
    最近更新 更多