首页 > 解决方案 > 如何在 mongodb 聚合中仅投影匹配的数组项?

问题描述

我有一个名为 的集合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 '$'."

标签: arraysmongodbaggregation-framework

解决方案


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 的帮助


推荐阅读