improve logic, no need for two cursors
Code clean up

Now cursor can get a query or aggregation command