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

时间:2017-07-04 10:02:25

标签: mongodb go mongodb-query mgo

我有两个系列 用户{id,name}和文件{id,userId,name}我想查找文件名为" abc.xyz"的所有文件,我尝试使用$ lookup编写代码但获取所有文件属于用户而不是按名称" abc.xyz"过滤它,我写了以下查询。

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"]}
           }
             }
         }
}
])

谢谢

1 个答案:

答案 0 :(得分:0)

  

我想查找文件名为“abc.xyz”的所有文件...但是获取所有文件属于用户而不是按名称“abc.xyz”过滤

根据您的上述问题,它也可以解释为“查找名称为abc.xyz的所有文件及其所有者信息”。

在这种情况下,最好先使用$match过滤文件集合,以过滤等于abc.xyz的文件名。这将限制查找users集合的文档数量,而不是对两个集合执行查找,然后执行过滤。

例如:

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

请注意,从files查看users,该集合现已撤消。示例结果将是:

  "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"
        }
      ]
    }
  ]

我还建议您查看:

相关问题