MongoDb-$lookup with where子句
考虑到这样的情况: 帖子:MongoDb-$lookup with where子句,mongodb,lookup,projection,Mongodb,Lookup,Projection,考虑到这样的情况: 帖子: post: { subject: 'test', category: 123, author: 1 } { id: 1, name: 'foo' } { id: 123, name: 'bar' } 用户: post: { subject: 'test', category: 123, author: 1 } { id: 1, name: 'foo' } { id: 123, name: 'bar' } 类别: post: {
post: {
subject: 'test',
category: 123,
author: 1
}
{
id: 1,
name: 'foo'
}
{
id: 123,
name: 'bar'
}
用户:
post: {
subject: 'test',
category: 123,
author: 1
}
{
id: 1,
name: 'foo'
}
{
id: 123,
name: 'bar'
}
类别:
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"
}
}
]
工作谢谢,有没有办法将查找字段作为单个项目(如findOne)而不是数组返回?您可以使用
arrayElemAt
和ifNull