V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
imldy
V2EX  ›  MongoDB

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

  •  
  •   imldy · 2023-02-17 20:40:24 +08:00 · 969 次点击
    这是一个创建于 432 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5472 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 05:50 · PVG 13:50 · LAX 22:50 · JFK 01:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.