我需要获取数组中存在的数组元素的总数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
作为答案
您非常接近解决方案 witm $map 。这是您必须做的:(随意将此控制台查询翻译成您的语言实现):
db.collection.aggregate([
{
$project: {
totalPosts: {
$sum: {
$map: {
input: "$products",
as: "products_inner",
in: {
$size: "$$products_inner"
}
}
},
}
}
},
])
将导致:
[
{
"_id": 2,
"totalPosts": 3
}
]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句