【发布时间】:2019-07-22 06:14:03
【问题描述】:
我需要获取 products 数组中存在的数组元素的总数。
到目前为止,我已经尝试使用$size=>$products 方法,但由于技术上只有两个数组,我得到的值是2,但我也想计算内部元素,以便得到所需的结果是3。
我知道我需要使用$unwind,但我无法弄清楚该方法。
{
_id:2,
card_pay:3998,
count:4598,
orders:2,
products:[
[
{
product_id:{
$oid:"5c63d418ae1db123d8048276"
},
amount:2499,
quantity:1,
status:1
},
{
product_id:{
$oid:"5c46f7f329067970211471a0"
},
amount:200,
quantity:2,
status:1
}
],
[
{
product_id:{
$oid:"5c63d3afae1db123d8048273"
},
amount:1499,
quantity:1,
status:1
}
]
]
}
编辑 1:
['$project'=>[ 'number_of_products'=> ['$size'=> '$products']
到目前为止,我已经尝试过了。
编辑 2:
到目前为止,我已经尝试过了。
[
'$project'=>[
'posts'=> [
'$map'=> [
'input'=> '$products',
'as'=> 'products_inner',
'in'=> [
'Count'=>[
'$size'=> '$$products_inner'
]
]
],
],
我得到了输出
[
{
_id: 2,
posts: [
{
Count: 2
},
{
Count: 1
}
]
}
]
现在我需要做的就是计算值以得到3 作为答案
【问题讨论】:
标签: php database mongodb mongodb-query aggregation-framework