0

I need to get the total number of array elements that are present inside the products array . So far i have tried using the $size=>$products approach but since technically there are two arrays only the value i get is 2 but i want to count the inner elements as well so that the desired result comes out to be 3.

I know i need to use $unwind but i cant figure out the approach.

{  
   _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
         }
      ]
   ]
}

EDIT 1: ['$project'=>[ 'number_of_products'=> ['$size'=> '$products']

So far i have tried this .

EDIT 2:

So far i have tried this .

[
	'$project'=>[
      'posts'=> [
         '$map'=> [
         'input'=> '$products',
         'as'=> 'products_inner',
         'in'=> [
               'Count'=>[
			   '$size'=> '$$products_inner'
         ]
   ]
 ],
						],

And i am getting the output

[
  {
    _id: 2,
    posts: [
      {
        Count: 2
      },
      {
        Count: 1
      }
    ]
  }
]

Now all i need to do is count the values to get 3 as the answer

0

1 Answer 1

1

You were very close to the solution witm $map . Here's what you have to do : (feel free to translate this console query into your language implementation) :

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

          }
        }
      },
    ]) 

Will result in :

[
  {
    "_id": 2,
    "totalPosts": 3
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.