我有两个系列 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/