How to perform text search together with geoNear?
Asked Answered
S

3

6

I am programing a Mongo query builder and I found two statements in documentation:

(Text search) The $match stage that includes a $text must be the first stage in the pipeline.

(Geo search) You can only use $geoNear as the first stage of a pipeline.

Which basically means the same, so... how to use those together?

Shanly answered 23/3, 2014 at 19:33 Comment(0)
H
3

I know this is an old question but I've recently had a similar problem so I thought I'd post my solution.

In my case I wanted:

  • first to use full-text search on user-supplied keywords as a filter
  • then, sort the results by distance from user-supplied coordinates
  • user could choose to provide keywords, location or both (the difficult case)

I tackled it with a block of code like this:


let query = {}

if(req.query.keywords){
  if(req.query.lng || req.query.lat){
    db.collection("service")
      .find({ $text: { $search: req.query.keywords }})
      .toArray()
      .then(docs => query._id = { $in: docs.map(doc => doc._id) })
  } else {
    query.$text = { $search: req.query.keywords }
  }
}

if(req.query.lat && req.query.lng){
  query.location = {
    $nearSphere: {
      $geometry: {
        type: "Point",
        coordinates: [req.query.lng, req.query.lat]
      }
    }
  }
}

db.collection("service").find(query)

Basically if a text search or a geo search is desired by itself, the appropriate query is built no problem. If both are needed, it does a text query first, and then passes the returned document ids as a filter to the second.

This is the most performant solution I could find!

Hampden answered 13/6, 2020 at 22:27 Comment(0)
T
1

I don't think you can. One thing I've done in the past is perform both queries and merge the results in the application code.

Terricolous answered 10/10, 2015 at 22:40 Comment(1)
mongodb forever holding Ls.Bartonbartosch
B
0

You can create a $match aggregation stage and use $geoWithin (or $geoIntersect) along with $text operator. That seems to be the best solution.

MongoDB Atlas Search also allows filtering for full-text and location at the same time.

Bohman answered 10/5, 2022 at 18:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.