如何避免在mongodb聚合查找重复的结果?



我总共需要查找两个集合。但是,在commentsLookup和likeeslookup字段中,输出结果不像我预期的那样重复。我试图用$group中的$addToSet取代$push,但$sort将从此集合中断开,导致错误的排序结果。我如何避免重复的结果或其他方法来解决这个问题?

下面是我的Mongo Playground:

https://mongoplayground.net/p/TKs7bPU_cVJ

有几件事,你有字段名倒置的喜欢连接,而且,当你做两个unwind,有多个实例的评论(例如,重复,正如你所暗示的)在你做你的组。

我会把这个问题当作两个独立的行动来处理:

  • 首先为注释(查找注释,unwind,查找用户组)获取所有内容
  • 然后让喜欢的一切看起来都很好(查找喜欢,unwind,查找用户组)

像这样:https://mongoplayground.net/p/JPX-q32HMjE

db.posts.aggregate([
{
$lookup: {
from: "comments",
localField: "id",
foreignField: "post_id",
as: "comments"
}
},
{
$unwind: "$comments"
},
{
$lookup: {
from: "users",
localField: "comments.user_id",
foreignField: "id",
as: "comments.user"
}
},
{
$set: {
"comments.user": {
$arrayElemAt: [
"$comments.user",
0
]
}
}
},
{
$group: {
_id: "$_id",
id: {
$first: "$id"
},
title: {
$first: "$title"
},
content: {
$first: "$content"
},
comments: {
$push: "$comments"
}
}
},
{
$lookup: {
from: "likes",
localField: "id",
foreignField: "post_id",
as: "likes"
}
},
{
$unwind: "$likes"
},
{
$lookup: {
from: "users",
localField: "likes.user_id",
foreignField: "id",
as: "likes.user"
}
},
{
$set: {
"likes.user": {
$arrayElemAt: [
"$likes.user",
0
]
}
}
},
{
$group: {
_id: "$_id",
id: {
$first: "$id"
},
title: {
$first: "$title"
},
content: {
$first: "$content"
},
comments: {
$first: "$comments"
},
likes: {
$push: "$likes"
}
}
}
])

最新更新