【发布时间】:2016-04-18 04:05:57
【问题描述】:
我有以下邮寄文件:
{
"_id" : ObjectId("56960cd909b0d8801d145543"),
"title" : "Post title",
"body" : "Post body"
}
{
"_id" : ObjectId("56960cd909b0d8801d145544"),
"_post": ObjectId("56960cd909b0d8801d145543"),
"body" : "Comment one"
}
{
"_id" : ObjectId("56960cd909b0d8801d145544"),
"_post": ObjectId("56960cd909b0d8801d145543"),
"body" : "Comment Two"
}
从我上面的文档中可以看出,这是我的帖子和评论实施的平面列表(如 SO)。如果帖子有 _post 字段,那么它是评论,但如果没有,它就是帖子本身。
当我查询问题56960cd909b0d8801d145543 时,我需要在以下视图中从 mongoDB 获得响应:
// query
Post.aggregate({_id: ObjectId("56960cd909b0d8801d145543")});
// result
{
"_id" : ObjectId("56960cd909b0d8801d145543"),
"title" : "Post title",
"body" : "Post body",
"comments" [{
"_id" : ObjectId("56960cd909b0d8801d145544"),
"_post": ObjectId("56960cd909b0d8801d145543"),
"body" : "Comment one"
},
{
"_id" : ObjectId("56960cd909b0d8801d145544"),
"_post": ObjectId("56960cd909b0d8801d145543"),
"body" : "Comment Two"
}]
}
我应该如何构造聚合 pipilenes 以获得上述结果?
【问题讨论】:
标签: mongodb mongoose aggregation-framework