场景是为评论寻找子评论 评论文档
{
"_id": {
"$oid": "63ed9bd52b031a24fdbe1e1e"
}
"creatorId": {
"$oid": "63e51a155ca7f018d6038967"
},
"text": "评论内容 0216"
}
子评论文档:
{
"_id": {
"$oid": "63ee03eb98b24f5603c044da"
},
"linkCommentId": {
"$oid": "63ed9bd52b031a24fdbe1e1e"
},
"replyToUserId": {
"$oid": "63e51a155ca7f018d6038967"
},
"creatorId": {
"$oid": "63e51a155ca7f018d6038967"
},
"text": "测试子评论 0216-2"
}
代码
[
{
$match:
{
_id: ObjectId("63ed9bd52b031a24fdbe1e1e"),
},
},
{ // 从子评论集合中找到评论的子评论(假设该评论不存在子评论,replies 为空数组)
$lookup:
{
from: "dynamicChildComment",
localField: "_id",
foreignField: "linkCommentId",
as: "replies",
},
},
{ // 展开子评论(得到一条没有 replies 的文档)
$unwind:
{
path: "$replies",
preserveNullAndEmptyArrays: true,
},
},
{ // 1 、给子评论寻找发布者,执行后:replies 对象只存在一个属性 creator ,值为空数组
$lookup:
{
from: "users",
localField: "replies.creatorId",
foreignField: "_id",
as: "replies.creator",
},
},
{ // 2 、执行后:replies 对象没有属性
$unwind:
{
path: "$replies.creator",
preserveNullAndEmptyArrays: true,
},
},
{ // 3 、执行后:replies 对象只存在一个属性 replyToUser ,值为空数组
$lookup:
{
from: "users",
localField: "replies.replyToUserId",
foreignField: "_id",
as: "replies.replyToUser",
},
},
{ // 4 、执行后:replies 对象没有属性
$unwind:
{
path: "$replies.replyToUser",
preserveNullAndEmptyArrays: true,
},
},
{
$group:
{
_id: "_id",
replies: {
$push: "$replies", // 到这里,就出现了一个 replies 数组,有一个空对象作为第 0 个元素
},
},
},
]
我该如何将 replies 数组变成空数组