[英]sum query mongodb php
I have this collection 我有这个系列
> db.test.find()
{ "_id" : ObjectId("5398ddf40371cdb3aebca3a2"), "name" : "ahmed", "qte" : 30 }
{ "_id" : ObjectId("5398de040371cdb3aebca3a3"), "name" : "demha", "qte" : 35 }
{ "_id" : ObjectId("5398de140371cdb3aebca3a4"), "name" : "ahmed", "qte" : 50 }
{ "_id" : ObjectId("5398de210371cdb3aebca3a5"), "name" : "ahmed", "qte" : 60 }
i would like to sum "qte" where "name"= "ahmed" and print the sum with php i know how to do with SQL but i have no idea how it is in mongodb. 我想总结“qte”,其中“name”=“ahmed”并用php打印总和我知道如何处理SQL,但我不知道它是如何在mongodb中。
Thanks :) 谢谢 :)
Use the aggregation framework. 使用聚合框架。
Assuming you have an the current collection as $collection
假设您将当前集合作为
$collection
result = $collection->aggregate(array(
array(
'$match' => array(
'name' => 'ahmed'
)
),
array(
'$group' => array(
'_id' => NULL,
'total' => array(
'$sum' => '$qte'
)
)
)
));
The two parts are the $match
to meet the criteria, and the $group
to arrive at the "total" using $sum
这两部分是符合条件的
$match
,以及使用$sum
到达“总计”的$group
See other Aggregation Framework Operators and the Aggregation to SQL Mapping chart for more examples. 有关更多示例,请参阅其他聚合框架操作符和聚合到SQL映射图表 。
This is done with an aggregate statement: 这是通过聚合语句完成的:
db.test.aggregate([
{
$match: {
name: "ahmed"
}
},
{
$group: {
_id:"$name",
total: {
$sum: "$qte"
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.