[英]MongoDb - $lookup with where clause
given something like this:给出这样的东西:
posts:帖子:
post: {
subject: 'test',
category: 123,
author: 1
}
users:用户:
{
id: 1,
name: 'foo'
}
category:类别:
{
id: 123,
name: 'bar'
}
How can I do the equivalent query to the sql:如何对 sql 执行等效查询:
SELECT *
FROM posts
JOIN users on posts.author = user.id
JOIN category on posts.category = category.id
WHERE users.name = 'foo' and category.name = 'bar' //this is the problem
I have been experimenting with project / lookups, but I have no idea how to add the 'where' in the lookup itself (or if that is even the proper way to query this.我一直在试验项目/查找,但我不知道如何在查找本身中添加“位置”(或者这是否是查询此的正确方法。
db.posts.aggregate(
[
{
$project: { 'subject': '$subject' },
},
{
$lookup: {
from: 'users',
localField: 'author',
foreignField: 'id',
as: 'test'
}
},
])
You have to use two $lookup
你必须使用两个
$lookup
[
{
"$lookup": {
"from": "users",
"localField": "post.author",
"foreignField": "id",
"as": "userJoin"
}
},
{
"$lookup": {
"from": "category",
"localField": "post.category",
"foreignField": "id",
"as": "categoryJoin"
}
},
{
$match: {
"categoryJoin.name": "bar",
"userJoin.name": "foo"
}
}
]
Working Mongo playground工作Mongo 游乐场
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.