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

标签 mongodb go mongodb-query mgo

我有两个系列 users{id, name} 和 files{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"]}
           }
             }
         }
}
])

谢谢

最佳答案

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"

根据您上面的问题,它也可以解释为“查找名称为 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"
        }
      ]
    }
  ]

我还建议您查看:

关于mongodb - Mongo如何加入两个集合并在第二个集合上添加条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44902874/

相关文章:

mongodb - 在数组中拉数组

mongodb - 多组 - 对数组内的每个值进行平均,而不会与另一个文档重复

javascript - 用express更新了文档

mongodb - 将外部数据导入 hdfs : is edge node a bottle neck?

javascript - 如何通过键从 MongoDB 集合中删除字段?

go - 根据字符在字符串中的位置获取字符

go - 删除 slice 中的元素

go - 如果没有类似 IDE 的特性,我们怎么知道包级变量是在哪里定义的?

mongodb - 需要光标选项

c# - 在 MongoDB 的嵌套文档中插入新文档