2016-11-19 126 views
0

比方說,我在MongoDB中有幾個集合,例如我希望得到這些字的交集。MongoDB從多個集合中獲取唯一字集

    fruit db 
     fresh fruit  |  dried fruit  | 
-------------------------|------------------------- 
{ "type": "apple" }   { type: "apple" } 
{ "type": "orange" }   { type: "peach" } 
{ "type": "peach" }   { type: "pineapple" } 
{ "type": "pear" }   { type: "grape" } 
{ "type": "watermelon" }  { type: "mango" } 
{ "type": "grape" }   { type: "plum" } 

,你可以從上面的例子看到,還有新鮮的水果和乾果,但也有每個集合之間相似的項目。也可能不止兩個集合。

我怎麼能在這個數據庫上運行一些查詢來查找每個集合中所有相同類型的水果。

既然蘋果,桃子和葡萄都在收藏中,有沒有辦法提取這樣的數據?

回答

0

您可以使用$lookup命令。要查找「freshFruit」常見的水果和「driedFruit」集合類似下面的查詢可用於:

db.freshFruit.aggregate([ 
    { 
     $lookup: { 
      from: "driedFruit", 
      localField: "type", 
      foreignField: "type", 
      as: "fruit" 
     } 
    }, 
    { 
     $match: { "fruit": { $ne: [] } } 
    } 
]); 
0
` 
db.freshFruit.aggregate([ 
     { 
     $lookup: { 
      from: "driedFruit", 
      localField: "type", 
      foreignField: "type", 
      as: "fruit" 
        } 
     }, 
     {$match: { "fruit": { $ne: [] } }}, 
     //Add another lookup and match to join another collection and at last use    $ group stage 
     { $group: { "_id": null,fruits : {$push :$type}}} 
]); 

` 水果你會得到所有存在集合中的所有水果