首页 > 解决方案 > Mongo 聚合,对数组元素调用 $match 不起作用。(包括复制)

问题描述

https://mongoplayground.net/p/dsMlfEdSkXP

我想查询广播者用户赞成的文档。在链接中,broadcasterUser id 是“23435553”

结果,不应返回带有 "_id": ObjectId("5e7d7c35d86d85088863f4df")," 的文档,因为广播公司的 voteType 是 "downVote"。

应该返回带有“_id”的文档:ObjectId("5e7d7c47d86d85088863f4e0"),因为广播者的 voteType 是“upVote”。

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

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

编辑:找到我的答案,谢谢@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" AND voteType="upVote" 的对象。

标签: mongodb

解决方案


要从数组中返回特定元素,您需要对$filter投影进行操作。而不是$match,您的最后一个管道查询将是这样的

{
    $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


推荐阅读