updated aggregate query code to allow completely custom queries