V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
imldy
V2EX  ›  MongoDB

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

  •  
  •   imldy · Feb 17, 2023 · 2121 views
    This topic created in 1166 days ago, the information mentioned may be changed or developed.

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

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

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1023 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 22:09 · PVG 06:09 · LAX 15:09 · JFK 18:09
    ♥ Do have faith in what you're doing.