margherita pizza
margherita pizza

Reputation: 7145

mongodb get array's count from all documents

I have a collection called users and that has a property called orders. orders is an array if present sometimes orders might not exist in the document.

I want to take all the orders count. I did this aggregation query.

[
  {
    $match: {
      orders: { $exists: true },
    },
  },
  {
    $project: {
      ordersCount: {
        $size: '$orders',
      },
    },
  },
]

This returns each user's orders count separately. But I want to take the sum of it.(Total orders count)

How do I achieve this with MongoDB?

Upvotes: 0

Views: 51

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17858

If you want to get all the sum of orders you can use the following aggregation:

[
  {
    $match: {
      orders: {
        $exists: true
      }
    }
  },
  {
    $group: {
      _id: null,
      totalCount: {
        $sum: {
          $size: "$orders"
        }
      }
    }
  }
]

Mongo Playground

Upvotes: 1

Related Questions