【发布时间】:2020-06-12 22:26:40
【问题描述】:
我有两个 mongo 文档集合(BlogPosts 和 UsersActivities),一旦用户查看或评论了博客文章,就会在 UsersActivities 中创建一条记录。博客文章按类型(A、B、...)分类。 UsersActivities.status 是一个枚举["Viewed", "Commented"]
带有一些虚拟数据的集合:
BlogPosts: [
{ _postId: 1, content: "some text 1", type: 'A'},
{ _postId: 2, content: "some text 2", type: 'A'},
{ _postId: 3, content: "some text 3", type: 'A'},
{ _postId: 4, content: "some text 4", type: 'B'}
]
UsersActivities:[
{ _userId: 1, _postId: 1, status: "Viewed"},
{ _userId: 1, _postId: 1, status: "Commented"},
{ _userId: 1, _postId: 2, status: "Viewed"},
{ _userId: 1, _postId: 4, status: "Viewed"},
{ _userId: 2, _postId: 1, status: "Viewed"}
]
我正在尝试编写一个查询,该查询将返回 A 类型的所有博客文章的不同列表,并且每篇文章的 userId 为 1 状态(如果查看并评论了文章,则状态应为“已评论”。如果没有状态找到,状态应该是一个空字符串)。查询结果应如下所示:
[
{_postId: 1, content: "some text 1", type: 'A', status: "Commented"},
{_postId: 2, content: "some text 2", type: 'A', status: "Viewed"},
{_postId: 3, content: "some text 3", type: 'A', status: ""}
]
这是我到目前为止编写的代码,但我卡住了,不知道如何继续。
BlogPosts.aggregate([
{
$lookup: {
localField: "_postId",
from: "UsersActivities",
foreignField: "_postId",
as: "UsersActivities",
},
},
{
$match: {
type: "A",
},
},
{
$unwind: {
path: "$UsersActivities",
preserveNullAndEmptyArrays: true,
},
},
{
$match: {
$or: [
{
"UsersActivities._userId": _userId,
},
{
"UsersActivities._userId": null,
},
],
},
},
])
请指教,我怎样才能达到要求的结果
【问题讨论】:
-
由于您要“加入”两个集合,因此聚合应使用允许这样做的$lookup 阶段。
标签: mongodb mongoose aggregation-framework