【问题标题】:MongoDB deep nested aggregation [duplicate]MongoDB深度嵌套聚合[重复]
【发布时间】:2018-11-17 13:31:46
【问题描述】:

tl;博士

我有什么:

db.posts.find()

[ 
  { authorId: 1, 
    text: "lorem",
    likes: 22 
    comments: [
      { commentatorId: 1, commentText: "cool"}, 
      { commentatorId: 2, commentText: "nice"}, 
      { commentatorId: 8, commentText: "trash"}
    ]
  }, 
  { authorId: 2, 
    text: "ipsum",
    likes: 33, 
    comments: [
      { commentatorId: 1, commentText: "cool"}, 
      { commentatorId: 1, commentText: "nice"}, 
      { commentatorId: 3, commentText: "trash"}
    ]
  },
  { authorId: 3, 
    text: "ipsum",
    likes: 44, 
    comments: [
      { commentatorId: 2, commentText: "cool"}, 
      { commentatorId: 2, commentText: "nice"}, 
      { commentatorId: 3, commentText: "trash"}
    ]
  },
  { authorId: 1, 
    text: "ipsum",
    likes: 55, 
    comments: [
      { commentatorId: 1, commentText: "cool"}, 
      { commentatorId: 2, commentText: "nice"}, 
      { commentatorId: 3, commentText: "trash"}
    ]
  },
]

我想要达到的目标:

{ 
 1: {posts: 2, likes: 77, comments: 4}, 
 2: {posts: 1, likes: 33, comments: 4},
 3: {posts: 1, likes: 44, comments: 3},
 8: {posts: 0, likes: 0,  comments: 1},
}

如您所见,这里的 authorId 和 commentatorId 字段包含一个 ObjectId 键,该键链接到另一个集合(比如说“用户”)。任何用户都可以作为作者或评论员。即使用户不写任何帖子,他仍然需要包含在聚合结果中。所有帖子都需要统计cmets个数,不仅仅是posts,authorId等于commentatorId。

【问题讨论】:

  • 你的问题是什么???
  • 一个聚合查询
  • 这不是问题。到目前为止你做了什么?什么阻碍了你?
  • 通过 authorId 字段执行 {$group: {...}} 我无法访问其他帖子的数据(其中包含该作者的 cmets 编号)

标签: javascript mongodb mongoose aggregation-framework


【解决方案1】:

我认为这是你想要的东西

db.posts.aggregate([
{$unwind:"$comments"},
{$group:{_id:"$authorId", 
"likes":{$addToSet:"$likes"}, "comments":{$addToSet:"$comments"}}},
{$project:{"likes":{$sum:"$likes"}, "posts":{$size:"$likes"}, "comments":{$size:"$comments"}}}
])

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2015-06-07
    • 2017-07-26
    • 2017-07-16
    • 2019-07-20
    • 1970-01-01
    相关资源
    最近更新 更多