node.js - Merge two MongoDB aggregates into one pipeline -
i have collection of population census , still don't dominate “aggregate” function results 1 query.
the collection has this format (plus iso 8601 timestamp). way, each time census conducted can register current ages , counts (which can add/modify/delete previous ages).
now have 2 “aggregate” queries to return this:
however need results 1 “aggregate” query, pipeline difficult me, , cannot statistics , “unwind” population sums…
any on how merge 2 queries, please? thank in advance!
try following aggregation pipeline, should give result of 2 queries:
db.collection('population').aggregate([ { "$unwind": "$population" }, { "$group": { "_id": 0, "doc": { "$push": "$$root" }, "average_age": { "$avg": "$population.age" }, "max_age": { "$max": "$population.age" }, "min_age": { "$min": "$population.age" }, "average_population": { "$avg": "$population.count" }, "max_population": { "$max": "$population.count" }, "min_population": { "$min": "$population.count" } } }, { "$unwind": "$doc" }, { "$group": { "_id": "$doc.population.age", "sum": { "$sum": "$doc.population.count" }, "average_age": { "$first": "$average_age"}, "max_age": { "$first": "$max_age"}, "min_age": { "$first": "$min_age"}, "average_population": { "$first": "$average_population"}, "max_population": { "$first": "$max_population"}, "min_population": { "$first": "$min_population"} } } ])
Comments
Post a Comment