Geo near and search operator in an aggregate pipeline index location

Hi all,

I am looking to use Atlas Search and the near operator to find records that satisfy both the search criteria and are near a given geo point. I created a 2d index for the field location, which follows the structure mentioned in the documentation.

When I try to find documents using only the near function, everything works fine. Similarly, using the search query with Atlas Search also works correctly. However, I am struggling to use both operators in the same aggregation query.

The error I encounter is:
Failed to run this query. Reason: geoWithin requires path 'location' to be indexed as 'geo'

The query I am running is:

  {
    $search: {
      index: "default",
      compound: {
        must: [
          {
            text: { query: "text", path: "*" },
          },
          {
            near: {
              path: "location",
              origin: {
                type: "Point",
                coordinates: [
                  45.464203, 9.189982,
                ],
              },
              pivot: 100000,
            },
          },
        ],
      },
    },
  },
]`
location field: 
![Capture|690x179](upload://1uFsgeGJfrga3yppxmekVT4YbBO.png)

Index field
![Capture|690x129](upload://9M9ciP3d9PwP1gVTKZpd5cYBynB.png)

Atlas Search index: 
![Capture|690x177](upload://fHEoJY4IUKezWFRrODDerYQBMkZ.png)

Query error: 
![Capture|690x426](upload://7zUViZDyGzTf6QJPU4dva39LGZx.png)

The same error was also raised from NodeJs. 
Any idea what I am doing wrong? 
Thanks in advance.
1 Like

It seems images didn’t make it through on your posting. Can you share your index configuration? Also, there appears to be an error with your text.path of “*”, when a wildcard only works as a path: {wildcard: "*"}construct.

Perhaps you could create a Code Playground for us to look at? Thanks!

1 Like

It seems you want the https://www.mongodb.com/docs/atlas/atlas-search/geoWithin/ operator instead of near . Would that work?

1 Like

I just happened to have an example of geoWithin laying around as a Playground. Adjust the radius to see the effect of matching/not-matching.

1 Like

This post to fix the image in the first post

Index field

The same error with geoWithin

here the link of the playground. Playground

Yes, this one was truely helpful. I was facing the same issue.

This error message is telling the story here. The field needs to be defined as defined here: https://www.mongodb.com/docs/atlas/atlas-search/field-types/geo-type/

See my playground link above for details.

Hi Erik, thanks for your help.
I was confused regarding the index because I used the native collection index.
I mean this one.


Thanks to you, the query now works.