对不起标题,我不知道如何更好地表达问题。
我试图将MongoDB文档中的书籍项目总花费加起来。这意味着在计算之前必须过滤数组,在计算总花费时才考虑购买书籍。
这是一个示例文档(我删除了一些字段,因此它不会太大):
{
"_id" : ObjectId("598cb3f4ca693a0688004e2a"),
"title" : {
"de" : "Another",
"ja" : "アナザー",
"roomaji" : "Another"
},
"total" : 4,
"volumes" : [
{
"volume" : 1,
"edition" : 1,
"price" : 7,
"releaseDate" : 1342051200,
"bought" : true,
"read" : true
},
{
"volume" : 2,
"edition" : 1,
"price" : 7,
"releaseDate" : 1347494400,
"bought" : true,
"read" : true
},
{
"volume" : 3,
"edition" : 1,
"price" : 7,
"releaseDate" : 1352419200,
"bought" : false,
"read" : false
},
{
"volume" : 4,
"edition" : 1,
"price" : 7,
"releaseDate" : 1357776000,
"bought" : false,
"read" : false
}
],
"releaseYear" : 2012
}
所以,我想总结所有卷对象的价格字段,但只有那些"买了"设置为true。结果我想得到这个输出:
{
"_id" : ObjectId(),
"title" : {
'de' : 'title'
},
"count" : 14
}
这是我的PHP代码
$result = $mongo->Book->aggregate([
[
'$group' => [
'_id' => '$_id',
'title' => ['$push' => '$title.de'],
'count' => [
'$sum' => [
'$map' => [
'input' => '$volumes',
'as' => 'vol',
'in' => [
'$cond' => [
[
'$eq' => ['$$vol.bought', true]
],
'$$vol.price',
0
]
]
],
]
]
]
],
[
'$sort' => [
'count' => -1
]
]
]);
但是计数总是会返回0.我做错了什么?