geoNear pipeline on view

Hello, I created a view containing some places with location, then I need to execute a geoNear pipeline on the view, to find the near places. From the guideline at,not%20support%20operations%20such%20as%3A&text=%24geoNear%20pipeline%20stage. it seems view doesn’t support geoNear because “Views are computed on demand during read operations, and MongoDB executes read operations on views as part of the underlying aggregation pipeline…” I am still not quite clear about the explanation, why I can’t execute the geoNear pipeline on a view? and is there any workaround solution? My view is created by a pipeline, i.e. pipeline Pa, if I copy the pipeline Pa in my search function, and add the operation of geoNear as new stage to the pipeline Pa, then I have pipeline Pb, will Pb work? If it can work, I don’t understand why the geoNear will not work on a view which is a result of the Pa?



Hi @Zhihong_GUO,

A geoNear query needs to run on a geo index and for that to happen it must be the first stage of aggregation. Now when you creating a view you are forcing the query to push all view stages before the query on the view.

Therefore it cannot guarantee geoNear will be first and thus forbidden.

What you can consider is either have a schedule $merge process to persist the view and geo index it to form a materialized view or $out to temp collection with an index and query it…


@Pavel_Duchovny, thanks for the quick answer.