用不存在的字段的子字段 lookup 时,分组后该字段值会变成空对象,如何变成 null

2023-02-17 20:40:24 +08:00
 imldy

场景是为评论寻找子评论 评论文档

{
  "_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 数组变成空数组

982 次点击
所在节点    MongoDB
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/917036

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX