【发布时间】: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