【问题标题】:$lookup and $unwind gives no result when nested array is empty当嵌套数组为空时,$lookup 和 $unwind 不给出任何结果
【发布时间】:2018-06-14 02:22:06
【问题描述】:

我有以下帖子集

{
    "_id" : ObjectId("5ad5ddb15e540442a7d4213c"),
    "content" : "content1",
    "comments" : [ObjectId("5af2a10dc56ad8378a3fbffa")]
}

我有以下 cmets 集合

{
    "_id" : ObjectId("5af2a10dc56ad8378a3fbffa"),
    "likeBy" : [ObjectId("5ac8ba3582c2345af70d4658")],
    "post" : ObjectId("5ad5ddb15e540442a7d4213c"),
    "comment" : "comment1",
}

我做了以下 $lookup 查询...当 cmets 数组有 ids 喜欢时,查询工作完美

"comments" : [ObjectId("5af2a10dc56ad8378a3fbffa")]

... 但是当 cmets 像

一样被清空时
    "comments" : []

然后它返回空数组...至少它应该返回第一个match条件{ $match: { _id: mongoose.Types.ObjectId(id) }}...

const post = await Post.aggregate([
          { $match: { _id: mongoose.Types.ObjectId(id) }},
          { $lookup: {
              from: 'comments',
              localField: 'comments',
              foreignField: '_id',
              as: 'comments'
            }
          },
          { $unwind: '$comments' },
          { $addFields: {
            "comments.isLiked": {
              $in: [ 
                mongoose.Types.ObjectId(req.user.id), 
                "$comments.likeBy"
              ]
            }
          }}
          { $group: {
              _id: '$_id',
              content: {$first: '$content'},
              comments: {$push: '$comments'}
            }
          }
        ])

所以我的预期结果应该是

    {
        "_id" : ObjectId("5ad5ddb15e540442a7d4213c"),
        "content" : "222222222222222222222222222222222222222222",
        "comments" : []
    }

【问题讨论】:

  • $unwind - 页面上关于空数组的内容是什么?
  • preserveNullAndEmptyArrays我用过但是不行
  • @NeilLunn 嗨...我在这里遗漏了什么...或者不可能...或者 mongodb 的能力和限制在这里结束...
  • 您缺少的是提供Minimal, Complete, and Verifiable example。问题在于$unwind 语句“当然”,其中$lookup 由于没有外部匹配而产生一个空数组。但实际上取决于您在您的问题中提供“可重复”的信息以及实际上可以从“您提供的数据”中获得的“预期结果”。您添加的文档没有重现结果,也没有任何可以从“您提供的文档”中获得的预期结果。

标签: node.js mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

只有 preserveNullAndEmptyArraystrue 默认为 false。

{
      $unwind: {
        path: '$toUserData',
        preserveNullAndEmptyArrays: true,
      },
    },

请参考链接:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/

【讨论】:

  • 如果我使用它,那么下一行会出现错误addFields...error: $in requires array
猜你喜欢
  • 2017-01-22
  • 2018-11-27
  • 2020-11-26
  • 1970-01-01
  • 2016-03-01
  • 2019-02-19
  • 2018-11-30
  • 1970-01-01
相关资源
最近更新 更多