【问题标题】:How to project only matched array item in mongodb aggregation?如何在 mongodb 聚合中仅投影匹配的数组项?
【发布时间】:2021-06-21 20:22:29
【问题描述】:

我有一个名为shows 的集合,文档为:

       {
            "url": "http://www.tvmaze.com/shows/167/24",
            "name": "24",
            "genres": [
                "Drama",
                "Action"
            ],
            "runtime": 60
        },
        {
            "url": "http://www.tvmaze.com/shows/4/arrow",
            "name": "Arrow",
            "genres": [
                "Drama",
                "Action",
                "Science-Fiction"
            ],
            "runtime": 60
        }

我想用genre 'Action' 搜索节目并将结果数组投影为

   {
        "url": "http://www.tvmaze.com/shows/167/24",
        "name": "24",
        "genres": [
            "Action" // I want only the matched item in 
         //my result array
        ],
        "runtime": 60
    } , //same for the second doc as well

如果我使用

db.shows.find({genres:'Action'}, {'genres.$': 1});

它可以工作,但在aggregate method$project 中同样不能工作

Shows.aggregate([
      {
        $match: { 'genres': 'Action'}
      },
      {
        $project: {
          _id: 0,
          url: 1,
          name: 1,
          runtime: 1,
          'genres.$': 1
        }
      }
]);

这是我在此聚合查询中遇到的错误

Invalid $project :: caused by :: FieldPath field names may not start with '$'."

【问题讨论】:

  • $ 投影仅适用于 find 方法,您可以在聚合查询中使用 $filter 聚合运算符。
  • 这能回答你的问题吗? How to filter array in a mongodb query
  • @turivishal,不,它没有回答,如果我使用正则表达式匹配流派“动作”怎么办,那么我在投影时该怎么做,它可能不是完全匹配。
  • 您可以在$filter 中使用$regexMatch 运算符。
  • 只需从两个匹配字符串中删除 / 斜线。

标签: arrays mongodb aggregation-framework


【解决方案1】:
db.collection.aggregate([
  {
    $match: {
      "genres": {
        $regex: "/^action/",
        $options: "im"
      }
    }
  },
  {
    $project: {
      _id: 0,
      url: 1,
      name: 1,
      runtime: 1,
      genres: {
        $filter: {
          input: "$genres",
          as: "genre",
          cond: {
            $regexMatch: {
              input: "$$genre",
              regex: "/^action/",
              options: "im"
            }
          }
        }
      }
    }
  }
])

这是我的解决方法,感谢@turivishal 的帮助

【讨论】:

    猜你喜欢
    • 2016-03-26
    • 2015-09-08
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 2020-08-31
    • 2021-03-07
    相关资源
    最近更新 更多