Mongo 聚合,在数组元素上调用 $match 不起作用.(包括复制) [英] Mongo aggregation, call $match on array elements not working. (reproduction included)

查看:59
本文介绍了Mongo 聚合,在数组元素上调用 $match 不起作用.(包括复制)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

https://mongoplayground.net/p/dsMlfEdSkXP

我想查询broadcasterUser 支持的文档.在链接中,broadcasterUser id 为23435553"

I want to query documents that the broadcasterUser upvoted. In the link, the broadcasterUser id is "23435553"

在结果中,不应返回带有 "_id": ObjectId("5e7d7c35d86d85088863f4df")," 的文档,因为广播公司的投票类型是 "downVote".

In the result, the document with "_id": ObjectId("5e7d7c35d86d85088863f4df")," should NOT be returned, because the broadcaster's voteType is "downVote".

应该返回带有_id"的文档:ObjectId("5e7d7c47d86d85088863f4e0"),因为广播公司的voteType是upVote".

The document with "_id": ObjectId("5e7d7c47d86d85088863f4e0") SHOULD be returned, because the broadcaster's voteType is "upVote".

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

Why is my $match condition not working?

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

找到我的答案,谢谢@prasad.https://mongoplayground.net/p/I_W0_BIIVVO

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",

        }
      },

    }
  },

])

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

I wasn't trying to do any array filtering. I was trying to filter documents, based on the presence of an object in an array.

第二个 $match 运算符的理想逻辑是找到建议文档,其中在 votes 数组中存在一个 user.id="23435553" AND voteType="upVote" 的对象.

The desired logic with the 2nd $match operator was "find suggestion documents where, in the votes array, there exists an object with user.id="23435553" AND voteType="upVote".

推荐答案

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

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"
                ]
              }
            ]
          }
        }
      }
    }
  }

解决方案也是在操场上完成的

The solution is also done in a playground

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

这篇关于Mongo 聚合,在数组元素上调用 $match 不起作用.(包括复制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆