我有MongoDB文档,其中包含以下数据(xxx)
{
"_id" : "48e5f6b1-026f-48b8-98cb-6572cfa0eaa6",
"esti_delivery_time" : "2015-1-1",
"original_price" : NumberInt(4060),
"price":109.2,
"code" : "JS1709137",
"updated_at" : ISODate("2017-09-13T06:01:18.000+0000"),
"created_at" : ISODate("2017-09-13T03:45:54.000+0000")
}
我想
SELECT "xxx" with SUM "price" and SUM "original_price"
答案 0 :(得分:0)
因为您需要price
和original_price
元素的总和,这意味着您需要按一些数据(一个或多个元素)对文档进行分组。对于此任务,您需要使用$group aggregator。
MongoDB PHP Driver documentation
示例:
$con = new MongoDB\Client('mongodb://localhost:27017', [], [
'typeMap' => [
'root' => 'array',
'document' => 'array',
'array' => 'array'
]
]);
$collection = $con->selectDatabase("db_name")->selectCollection("collection_name");
$cursor = $collection->aggregate([
[
'$group' => [
"_id" => '$code',
"sum_price" => ['$sum' => '$price'],
"sum_original_price" => ['$sum' => '$original_price']
]
]
]);
答案 1 :(得分:-1)