MongoDB聚合-过滤子数组并投影其部分数据

时间:2019-01-01 19:36:50

标签: mongodb aggregation-framework

我有一些看起来像这样的文件

每个文档都包含“书”和“电影”,但我不知道每个书有多少。

{ 
    "_id" : 1, 
    "books" : [
        {
            "title" : "Philosopher's Stone", 
            "PopularVote" : 10, 
            "CriticsVote" : 9 
        },
        {
            "title" : "Chamber of Secrets", 
            "PopularVote" : 8, 
            "CriticsVote" : 6 
        },
        {
            "title" : "Prisoner of Azkaban", 
            "PopularVote" : 2, 
            "CriticsVote" : 10 
        }
    ],
    "movies" : [
        {
            "title" : "Goblet of Fire", 
            "PopularVote" : 5, 
            "CriticsVote" : 10 
        },
        {
            "title" : "Order of the Phoenix", 
            "PopularVote" : 8, 
            "CriticsVote" : 9 
        }
    ]       
}       

我只想选择在PopularVote或CriticsVote上获得10的数组,并仅投影标题。结果应如下所示。

{ 
    "_id" : 1, 
    "books" : [
        {
            "title" : "Philosopher's Stone",  
        },
        {
            "title" : "Prisoner of Azkaban",  
        }
    ],
    "movies" : [
        {
            "title" : "Goblet of Fire", 
        }
    ]       
}    

我尝试了$filtercond的所有组合:但是失败了。

谢谢!

p.s。哈利·波特迷,这只是一个数据示例,并不反映我对书和电影的看法(-:

1 个答案:

答案 0 :(得分:1)

使用$addFields$filter来替换现有的booksmovies并应用过滤条件,然后可以使用$project仅获取标题,请尝试:

db.col.aggregate([
    {
        $addFields: {
            books: {
                $filter: {
                    input: "$books",
                    as: "b",
                    cond: {
                        $or: [
                            { $eq: [ "$$b.PopularVote", 10 ] },
                            { $eq: [ "$$b.CriticsVote", 10 ] }
                        ]
                    }
                }
            },
            movies: {
                $filter: {
                    input: "$movies",
                    as: "m",
                    cond: {
                        $or: [
                            { $eq: [ "$$m.PopularVote", 10 ] },
                            { $eq: [ "$$m.CriticsVote", 10 ] }
                        ]
                    }
                }
            }
        }
    },
    {
        $project: {
            "books.title": 1,
            "movies.title": 1
        }
    }
])