0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.