@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 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 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.