MongoDb - $lookup with where 子句
MongoDb - $lookup with where clause
给出这样的东西:
帖子数:
post: {
subject: 'test',
category: 123,
author: 1
}
用户:
{
id: 1,
name: 'foo'
}
类别:
{
id: 123,
name: 'bar'
}
如何对 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
我一直在试验项目/查找,但我不知道如何在查找本身中添加 'where'(或者这是否是查询它的正确方法。
db.posts.aggregate(
[
{
$project: { 'subject': '$subject' },
},
{
$lookup: {
from: 'users',
localField: 'author',
foreignField: 'id',
as: 'test'
}
},
])
你必须使用两个 $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"
}
}
]
给出这样的东西:
帖子数:
post: {
subject: 'test',
category: 123,
author: 1
}
用户:
{
id: 1,
name: 'foo'
}
类别:
{
id: 123,
name: 'bar'
}
如何对 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
我一直在试验项目/查找,但我不知道如何在查找本身中添加 'where'(或者这是否是查询它的正确方法。
db.posts.aggregate(
[
{
$project: { 'subject': '$subject' },
},
{
$lookup: {
from: 'users',
localField: 'author',
foreignField: 'id',
as: 'test'
}
},
])
你必须使用两个 $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"
}
}
]