Is there a way of counting the occurrence of elements in an array within a document without using $unwind?
To put it another way, is there an equivalent of Python list count?
Is there a way of counting the occurrence of elements in an array within a document without using $unwind?
To put it another way, is there an equivalent of Python list count?
You will need $reduce and potentially $addToSet, $filter or some other operators.
With sample documents and expected result the recommendation can be more specific.
Thanks for your response.
I’ll be more specific:
Within a document we have an array field that looks like this:
“grades”:[“A”, “E”, “D”, “A”, “E”, 'C", “A”, “D”, “C”, “B”]
I need to extract documents that have two or more “A” grades.
You pointed me in the right direction. Thanks. This query did it.
q1 = [{
"$project": {
"countA": {
"$reduce": {
"input": "$grade_list",
"initialValue": 0,
"in": {
"$cond": [
{ "$eq": ["$$this", "A"] },
{ "$add": ["$$value", 1] },
"$$value"
]
}
}
}
}
}]
This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.