douren9077 2017-07-04 10:02
浏览 231

Mongo如何加入两个集合并在第二个集合上添加条件

I have two collections users{id, name} and files{id, userId, name} I want to find all the files whose file name "abc.xyz", I tried to write a code using $lookup but getting all the files belong to user and not filtering it by name "abc.xyz", I have written following query.

db.user.aggregate([
{"$lookup": 
    {
        "from": "files", 
        "localField": "id", 
        "foreignField": "userId", 
        "as": "fileList"
    }
},
{"$project": { "filList":{
    "$filter": {
                    "input":"$fileList",
                    "as":"file"
                    "cond": {"$eq": ["$file.name","abc.xyz"]}
           }
             }
         }
}
])

Thank you

  • 写回答

1条回答 默认 最新

  • duandianzhong8315 2017-07-05 05:58
    关注

    I want to find all the files whose file name "abc.xyz" … but getting all the files belong to user and not filtering it by name "abc.xyz"

    Based on your question above, it could also be interpreted as "Find all files with name abc.xyz along with its owner information".

    In which case, it would be better to filter the files collection first using $match to filter file name equal to abc.xyz. This would limit the number of documents to look-up into users collection, instead of perfoming lookup for both collections then perform filtering.

    For example:

    db.files.aggregate([
        {"$match": {"name":"abc.xyz"}},
        {"$lookup": {
                    "from": "users", 
                    "localField": "userId", 
                    "foreignField": "_id", 
                    "as": "users"
                     }
         }]);
    

    Please note that the collection is now reversed, from files looking up into users. An example result would be:

      "result": [
        {
          "_id": 111,
          "userId": 999,
          "name": "abc.xyz",
          "owner": [
            {
              "_id": 999,
              "name": "xmejx"
            }
          ]
        },
        {
          "_id": 222,
          "userId": 998,
          "name": "abc.xyz",
          "owner": [
            {
              "_id": 998,
              "name": "kalwb"
            }
          ]
        }
      ]
    

    I would also recommend to check out:

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测