MongoDB Aggregate multiple count and latest date -
i'm trying mongo 3.0 query beyond depth. hoping bit of help. basically, database has transcription records whereby there given user name, project id, expedition id, , finished_date. fields i'm interested in. project have multiple expeditions, each expedition multiple transcriptions.
i display information given user in stats page given project. display user name, total project transcriptions user submitted whole project, total participated expeditions number of expeditions user participated in across project, , last date user performed transcription.
so far, it's easy enough total project transcriptions using count on user_name , matching project_id
db.transcriptions.aggregate([ { "$match" : {"projectid" => 13}}, { "$group": { "_id": "$user_name", "transcriptioncount" : {"$sum" : 1 } } } ]) each transcription document has expeditionid field (4, 7, 9, 10, etc.) , finished_date. if user performed 100 transcriptions, participating in expedition 7 , 10, total participated expeditions = 2 last finished_date being date showing last time user performed transcription. example of returned record:
user_name: john smith transcriptioncount: 100 expeditioncount: 2 last_date: 2017-08-15 hope explained enough. appreciate help.
you can try below aggregation.
db.transcriptions.aggregate([ { "$match": { "projectid" => 13 } }, { "$sort": { "finished_date": -1 } }, { "$group": { "_id": "$user_name", "transcriptioncount": { "$sum": 1 }, "expedition": { "$addtoset": "$expedition_id" }, "last_date": { "$first": "$finished_date" } } }, { "$project": { "_id": 0, "user_name": "$_id", "transcriptioncount": 1, "expeditioncount": { "$size": "$expedition" }, "last_date": 1 } } ])
Comments
Post a Comment