arrays - 如何在 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 '$'."
解决方案
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 的帮助
推荐阅读
- snowflake-cloud-data-platform - 雪花卡夫卡连接器,无法登录
- c# - 提取 FDF 注释
- sql - 相当于 Oracle 11g 中 dba_credentials 的视图
- json - Scala:根据内部值编辑/修改 json 字符串
- python-3.x - 将字符串与键进行比较并返回字符串模糊匹配后的值
- firebase - 从现有文件创建 Firestore 数据库
- visual-studio - 部署在本地计算机上的 Unity UWP XAML 应用程序按钮不响应鼠标单击
- c - FFMPEG - 将 .wav 文件编码为 G711
- sql - 从 PostgreSQL 的有序日期开始
- python-3.x - 确定字符串中的字母数字模式