MongoDB从多个集合中获取唯一字集

问题描述:

比方说,我在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" } 

,你可以从上面的例子看到,还有新鲜的水果和干果,但也有每个集合之间相似的项目。也可能不止两个集合。

我怎么能在这个数据库上运行一些查询来查找每个集合中所有相同类型的水果。

既然苹果,桃子和葡萄都在收藏中,有没有办法提取这样的数据?

您可以使用$lookup命令。要查找“freshFruit”常见的水果和“driedFruit”集合类似下面的查询可用于:

db.freshFruit.aggregate([ 
    { 
     $lookup: { 
      from: "driedFruit", 
      localField: "type", 
      foreignField: "type", 
      as: "fruit" 
     } 
    }, 
    { 
     $match: { "fruit": { $ne: [] } } 
    } 
]); 

` 
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}}} 
]); 

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