How to count/sum array on mongodb?

Member

by lily , in category: MySQL , 3 months ago

How to count/sum array on mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 3 months ago

@lily 

To count or sum an array in MongoDB, you can use the aggregate method along with the $unwind, $group, and $sum operators. Here's an example of how you can count or sum an array in MongoDB:

  1. Counting elements in an array:
1
2
3
4
db.collection.aggregate([
  { $unwind: "$arrayField" },
  { $group: { _id: null, count: { $sum: 1 } } }
])


Replace collection with the name of your MongoDB collection and arrayField with the name of the field that contains the array you want to count. This query will return the total number of elements in the array.

  1. Summing elements in an array:
1
2
3
4
db.collection.aggregate([
  { $unwind: "$arrayField" },
  { $group: { _id: null, total: { $sum: "$arrayField" } } }
])


This query will return the sum of all elements in the array.


Remember to replace collection and arrayField with your actual collection and field names.

Related Threads:

How to get sum of count of the columns in oracle?
How to sum array column in mysql?
How to count documents in MongoDB using PHP?
How to count array elements occurrences in presto?
How to return partial array match in inner array of mongodb?
How to properly unwind my array in mongodb?