【问题标题】:MongoDB getting unique set of words from multiple collectionsMongoDB 从多个集合中获取唯一的单词集
【发布时间】:2017-04-03 01:00:30
【问题描述】:

假设我在 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"  }

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

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

既然苹果、桃子和葡萄都在两个集合中,有没有办法提取这样的数据?

【问题讨论】:

    标签: mongodb database nosql


    【解决方案1】:

    您可以为此使用$lookup 命令。要在“freshFruit”和“driedFruit”集合中查找常见水果,可以使用如下查询:

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

    【讨论】:

      【解决方案2】:
      `
      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}}}
      ]);
      

      ` 在水果中,您将获得所有集合中存在的所有水果

      【讨论】:

        猜你喜欢
        • 2020-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多