How to count/sum array on mongodb?

Member

by lily , in category: MySQL , a day ago

How to count/sum array on mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 9 hours 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.