我有2个mongodb集合:“用户”和“帖子”。
// users
{
_id,
username,
password,
privacy_level
}
// posts
{
_id,
user_id,
text,
timestamp
}
是否可以根据用户的隐私级别(“公开”)提取所有帖子。在SQL中,我会这样做:
SELECT
_id,
text,
timestamp
FROM
posts
JOIN
users
ON
posts.user_id = users._id
WHERE
users.privacy_level = 'public'
是否可以在mongodb中实现这种查询逻辑?
答案 0 :(得分:3)
是的,您可以使用$lookup来轻松实现这一点,它是SQL连接的Mongo等价物。这是一个从users集合开始查询的示例:
db.users.aggregate([
{
$match: {
privacy_level: "public"
}
},
{
"$lookup": {
"from": "posts",
"localField": "_id",
"foreignField": "user_id",
"as": "posts"
}
},
{
$unwind: "$posts"
},
{
$project: {
_id: "$posts._id",
text: "$posts.text",
timestamp: "$posts.timestamp"
}
}
])
答案 1 :(得分:1)
您可以尝试$lookup运算符加入收藏集,
$lookup
加入用户集合$match
privacy_level
是公开的$project
删除多余的字段db.posts.aggregate([
{
$lookup: {
from: "users",
localField: "user_id",
foreignField: "_id",
as: "user"
}
},
{ $match: { "user.privacy_level": "public" } },
{
$project: {
user: 0,
user_id: 0
}
}
])