MongoDB聚合 - 返回与查询不匹配的文档的默认值

时间:2015-07-09 10:51:47

标签: mongodb nosql-aggregation

我无法确定正确的汇总管道操作以返回我需要的结果。

我有一个类似于以下的集合: -

{
    "_id" : "writer1",
    "Name" : "writer1",
    "Website" : "website1",
    "Reviews" : [
            {
                    "Film" : {
                            "Name" : "Jurassic Park",
                            "Genre" : "Action"
                    },
                    "Score" : 4
            },
            {
                    "Technology" : {
                            "Name" : "Mad Max",
                             "Genre" : "Action"
                    },
                    "Score" : 5
            }
    ]
}
{
    "_id" : "writer2",
    "Name" : "writer2",
    "Website" : "website1",
    "Reviews" : [           
            {
                    "Technology" : {
                            "Name" : "Mad Max",
                             "Genre" : "Action"
                    },
                    "Score" : 5
            }
    ]
}

到目前为止,这是我的汇总: -

db.writers.aggregate([
    { "$unwind" : "$Reviews" },
    { "$match" : { "Reviews.Film.Name" : "Jurassic Park" } },
    { "$group" : { "_id" : "$Website" , "score" : { "$avg" : "$Reviews.Score" },
        writers :{ $push: { name:"$Name", score:"$Reviews.Score" } }
    }}
])

这只返回对匹配影片进行评论的作家,以及只有至少有1位作者评论过该影片的网站, 但是,我需要返回包含所有作家列表的所有网站,如果他们没有为指定的电影撰写评论,则得分为0。

所以,我现在得到: -

{ "_id" : "website1", "score" : 4, "writers" : [ { "name" : "writer1", "score" : 4 } ] }

当我真正需要时: -

{ "_id" : "website1", "score" : 2, "writers" : [ { "name" : "writer1", "score" : 4 },{ "name" :"writer2", "score" : 0 } ] }

有人能指出我正确的方向吗?

干杯

0 个答案:

没有答案