2012-04-18 86 views
-1

我是MongoDB的新手,這是我第一次使用MapReduce。MapReduce for PHP MongoDB?

我有兩個類別:商店和產品具有以下模式

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類似的聲明MongoDB的MapReduce的與檢索用的名字商店'L'產品具有'已啓用'=> 1

我該怎麼做?謝謝。

+2

您是否需要頻繁地將這些集合加入到一起?如果是這樣,你可能要重新考慮使用MongoDb或重新考慮一下你的模式。 – 2012-04-18 20:55:26

+0

你好,你有沒有這個運氣? Marc的回答看起來相當不錯,我認爲應該得到某種反饋。 – halfer 2015-10-11 21:56:18

+0

實際上,我們搬到了一個sql友好的數據庫。蒙戈對其他業務好 – 2015-10-12 15:14:48

回答

0

簡短的回答:你不能這樣做(使用單個MapReduce命令)。

長答案:MongoDB中的MapReduce作業只能在單個集合上運行,並且不能引用該進程中的其他集合。因此,這裏不提供SQL的012行爲,新的彙總框架也僅在一個集合上運行。

我建議兩部分的解決方案:

  1. 獲取所有的商店名稱爲 「L」。

  2. 撰寫並運行map-reduce命令,該命令將根據此預先計算的商店列表檢查每個產品文檔。

+0

你能幫助我使用MapReduce命令嗎?我讀了一點,但我不知道如何在這裏應用它。 – 2012-04-19 06:47:19

+0

我想看到比「我讀一點」更多的努力。 – 2012-04-19 22:51:18

1

應該可以在沒有Map Reduce操作的情況下檢索所需的信息。

您可以首先查詢匹配{'enabled':1}的文檔的「Products」集合,然後從該查詢中獲取$ 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" } 
> 

首先找到所有匹配的文件{ 「已啓用」: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數組tha中查詢具有_id值的文檔的商店集合t也匹配{名稱:「L」}。

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

以前有人問過關於做與Mongo等同的加入操作的類似問題。這個問題提供了一些鏈接可以爲您提供額外的指導:
How to join MongoDB collections in Python?

如果你想用地圖試驗降低,這裏是從誰使用增量的Map Reduce操作結合用戶在博客帖子的鏈接來自兩個集合的值。
http://tebros.com/2011/07/using-mongodb-mapreduce-to-join-2-collections/

希望以上將允許您從您的收藏中檢索所需的信息。