I am attempting to run a custom aggregation query with Spring Boot and MongoDB that returns the sum of fields in a sub-document that match a certain criteria.
Currently, I have a query that returns the sum of fields in a sub-document, but does not take into consideration the matching of criteria.
Working query:
@Aggregation(pipeline = {"{'$project': {'_id': '$_id', 'date': '$date', \n" + " 'confirmed': {'$sum': '$states.confirmed'}, \n" + " 'deaths': {'$sum': '$states.deaths'}, \n" + " 'recovered': {'$sum': '$states.recovered'}, \n" + " 'active': {'$sum': '$states.active'}}}}" }) AggregationResults<LineChart> aggregateAllStates(Sort sort); Returns:
[ { "date": "2020-04-12", "confirmed": 555613, "deaths": 22107, "active": 500306, "recovered": 67139 }, { "date": "2020-04-13", "confirmed": 580876, "deaths": 23633, "active": 615609, "recovered": 78924 }, { "date": "2020-04-14", "confirmed": 607926, "deaths": 25931, "active": 534076, "recovered": 85408 }, etc... ] The next aggregation does not work:
@Aggregation(pipeline = {"{'$unwind':{path:'$states'}},\n" + " {'$match': {'states.state': 'alabama'}},\n" + " {'$project':{_id:'$_id', date: '$date',\n" + " confirmed: {'$sum': '$states.confirmed'},\n" + " active: {'$sum': '$states.active'},\n" + " deaths: {'$sum': '$states.deaths'},\n" + " recovered: {'$sum': '$states.recovered'}\n" + " }}" }) AggregationResults<LineChart> aggregateOneState(String name, Sort sort); Returns:
[ { "date": "2020-04-12", "confirmed": null, "deaths": null, "active": null, "recovered": null }, { "date": "2020-04-12", "confirmed": null, "deaths": null, "active": null, "recovered": null }, { "date": "2020-04-12", "confirmed": null, "deaths": null, "active": null, "recovered": null }, etc.. ] Running this query in the mongo shell works perfectly fine. In Spring it returns a lot more data (pretty sure it is returning the unwound data) with all fields nulled out.
db.us_collection.aggregate([ {'$unwind':{path:'$states'}}, {'$match': {'states.state': 'alabama'}}, {'$project':{_id:'$_id', date: '$date', confirmed: {'$sum': '$states.confirmed'}, active: {'$sum': '$states.active'}, deaths: {'$sum': '$states.deaths'}, recovered: {'$sum': '$states.recovered'} }}, {'$sort':{date:-1}} ]) https://stackoverflow.com/questions/66450656/aggregation-annotation-not-working-with-unwind-and-match March 03, 2021 at 12:07PM
没有评论:
发表评论