Reputation: 601
Suppose we have an array in the aggregation pipeline:
{
dates: [
"2019-01-29",
"2019-01-29",
"2019-01-29",
"2019-01-29",
"2019-02-06",
"2019-02-06",
"2019-02-06",
"2019-02-08",
"2019-06-04",
"2019-06-25",
"2019-07-26",
"2019-08-15",
"2019-08-15",
]
}
How to find an average count of the days in such an array?
The next stage of the pipeline is supposed to look like this:
dates : {
"2019-01-29": 4,
"2019-02-06": 3,
"2019-02-08": 1,
"2019-06-04": 1,
"2019-06-25": 1,
"2019-07-26": 1,
"2019-08-15": 2
}
But the final result is supposed to look like this:
avg_day_count: 1.85714285714
I.e. the average count of the days.
The sum of all days divided by the count of unique days.
Upvotes: 3
Views: 72
Reputation: 14698
You can achieve this without any $group
logic with a single $project
;
db.collection.aggregate([
{
"$project": {
"result": {
$divide: [
{ $size: "$dates" },
{ $size: { $setUnion: [ "$dates" ] } }
]
}
}
}
])
will give out;
[
{
"_id": ...,
"result": 1.8571428571428572
}
]
check the code interactively on MongoPlayground
Upvotes: 3