lib: optimize counting documents