【问题标题】:Count number of values inside an array mongo PHP [duplicate]计算数组mongo PHP中的值数[重复]
【发布时间】: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


    【解决方案1】:

    您非常接近 witm $map 的解决方案。这是您必须做的:(请随意将此控制台查询翻译成您的语言实现):

     db.collection.aggregate([
          {
            $project: {
              totalPosts: {
                $sum: {
                  $map: {
                    input: "$products",
                    as: "products_inner",
                    in: {
                      $size: "$$products_inner"
                    }
                  }
                },
    
              }
            }
          },
        ]) 
    

    将导致:

    [
      {
        "_id": 2,
        "totalPosts": 3
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 2018-09-22
      • 2022-01-12
      • 1970-01-01
      相关资源
      最近更新 更多