Mongo聚合,对数组元素不起作用调用$ match。 (包括复制)

 收藏

https://mongoplayground.net/p/dsMlfEdSkXP

我想查询broadcasterUser推荐的文档。在链接中,broadcasterUser id为“ 23435553”

结果,不应返回带有“ _id”:ObjectId(“ 5e7d7c35d86d85088863f4df”),“的文档,因为广播公司的表决类型为” downVote“。

应该返回带有“ _id”的文档:ObjectId(“ 5e7d7c47d86d85088863f4e0”),因为广播公司的表决类型为“ upVote”。

为什么我的$ match条件不起作用?

  {
    $match: {
      "votes.user.id": "23435553",
      "votes.voteType": "upVote",
    }
  }

EDIT: Found my answer, thanks @prasad. https://mongoplayground.net/p/I_W0_BIIVVO

db.suggestions.aggregate([
  {
    $match: {
      "channelId": "23435553",

    }
  },
  {
    $lookup: {
      from: "votes",
      localField: "_id",
      foreignField: "suggestionId",
      as: "votes"
    }
  },
  {
    $match: {
      "votes": {
        "$elemMatch": {
          "user.id": "23435553",
          "voteType": "upVote",

        }
      },

    }
  },

])

我没有尝试做任何数组过滤。我试图根据数组中对象的存在来过滤文档。

使用第二个$ match运算符所需的逻辑是“查找建议文档,其中的投票数组中存在一个具有user.id =“ 23435553”和voteType =“ upVote”的对象。

回复
  • To return specific elements from an array, you need to do $filter on your projection. instead of $match, your last pipeline query will be something like this

    {
        $project: {
          _id: 1, user: 1,
          votes: {
            $filter: {
              input: "$votes",
              as: "item",
              cond: {
                $and: [
                  {
                    $eq: [
                      "$$item.user.id",
                      "23435553"
                    ]
                  },
                  {
                    $eq: [
                      "$$item.voteType",
                      "upVote"
                    ]
                  }
                ]
              }
            }
          }
        }
      }
    

    该解决方案也在操场上完成

    https://mongoplayground.net/p/J9O-HzHnQNP