Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Searching on Your Location with Atlas Search and Geospatial Operators

TwitterFacebookRedditLinkedInHacker News

When thinking about full-text search, text and other string data is probably the first thing to come to mind. In fact, if you’ve been keeping up with my tutorials, you might remember Building an Autocomplete Form Element with Atlas Search and JavaScript or Visually Showing Atlas Search Highlights with JavaScript and HTML, both of which were on text search examples in MongoDB Atlas Search.

Being able to use natural language search on text data is probably one of the most popular use-cases, but there are scenarios where you might need to narrow the results even further.

Let’s say you’re building a restaurant review application like Yelp or a bed and breakfast booking system like Airbnb. Sure, you’ll enter some kind of text criteria for what you’re looking for, but there’s also a location aspect to it. For example, if you want to find a place to get a cheeseburger within walking distance of your current location, you probably don’t want your search results to contain entries from another country. This is an example of a geo search, where you would want to return results based on location coordinates.

In this tutorial, we’re going to see how to use Atlas Search and the compound operator to search based on text entered and within a certain geographical area. For the text entered, we’ll use the autocomplete operator, and for the geospatial component, we’ll use the geoWithin operator.

To get an idea of what we want to accomplish, take a look at the following animated image:

Compounding Text and Geospatial Searches in Atlas Search

The above example will look similar to what I wrote about in the Building an Autocomplete Form Element with Atlas Search and JavaScript tutorial with the exception that this time, we are returning results based on a provided location.

The Requirements

For this tutorial, we’ll be using JavaScript and Node.js with MongoDB Atlas. There will be a frontend and backend component, but without too many prior requirements. To be successful and follow along, you’ll need the following:

  • MongoDB Atlas (M0+ cluster)
  • Node.js (15.9.0+)
  • The sample_airbnb sample dataset (load it for free in Atlas).

The above versions are just the versions that I’m using. You might have success with an older version of Node.js as well. For MongoDB Atlas, you can use a FREE M0 cluster or something more powerful.

We’re going to be using a sample dataset for this example. You can learn more about sample_airbnb and the others in the documentation.

Building a Search API with Node.js and Express

We’re going to build an API, but it is going to have a single endpoint. The purpose of this API is to allow our front end to interact with MongoDB.

On your computer, create a new directory for our back end and execute the following from the command line:

npm init -y
npm install mongodb express cors

The above commands will create a new package.json file and then download the MongoDB and Express Framework dependencies. Because we’re going to have our back end and front end running locally on different ports, installing a cross-origin resource sharing (CORS) package is also necessary.

Rather than going back to the basics with MongoDB, we’re going to use the following boilerplate JavaScript code:

const { MongoClient } = require("mongodb");
const Express = require("express");
const Cors = require("cors");

const app = Express();

app.use(Express.json());
app.use(Express.urlencoded({ extended: true }));
app.use(Cors());

const client = new MongoClient(
    process.env["ATLAS_URI"], 
    { 
        useUnifiedTopology: true 
    }
);

var collection;

app.post("/search", async (request, response, next) => {
    console.log(JSON.stringify(request.body));
    try {
        let result = await collection.aggregate([/* Search Logic Here */]).toArray();
        response.send(result);
    } catch (e) {
        response.status(500).send({ message: e.message });
    }
});

app.listen(3000, async () => {
    try {
        await client.connect();
        collection = client.db("sample_airbnb").collection("listingsAndReviews");
    } catch (e) {
        console.error(e);
    }
});

Add the above code to a main.js file within your project directory. If you want a quick start for MongoDB with Node.js, Lauren Schaefer wrote a multi-part series to get you up to speed.

There is one thing to note in the above code:

const client = new MongoClient(
    process.env["ATLAS_URI"], 
    { 
        useUnifiedTopology: true 
    }
);

My MongoDB Atlas connection information is being stored as an environment variable on my computer. While environment variables are the safest approach, make sure you swap it with whatever you plan to use.

With the boilerplate code out of the way, we can focus on what matters for this example: the aggregation pipeline for searching on text and geospatial data. However, before we start writing pipeline stages, we need to properly index our data for search.

In MongoDB Atlas, select the top-level Search tab after choosing one of your clusters. Within this tab, select the Create Index button which will bring you into a configuration wizard for creating Atlas Search indexes.

MongoDB Atlas Search Index Configuration Wizard

Rather than using the visual editor to create an index, we’re going to use the JSON Editor with the following configuration. Provide sample_airbnb as the database and listingsAndReviews as the collection. You can copy and paste the following index configuration:

{
    "mappings": {
        "dynamic": false,
        "fields": {
            "address": {
                "fields": {
                    "location": {
                        "type": "geo"
                    }
                },
                "type": "document"
            },
            "name": [
                {
                    "foldDiacritics": false,
                    "maxGrams": 7,
                    "minGrams": 3,
                    "tokenization": "edgeGram",
                    "type": "autocomplete"
                }
            ]
        }
    }
}

While the name of the index doesn’t impact its functionality, we’re going to name it autocomplete and reference it within our Node.js application. To break down what the above index does, we are indexing two fields within the documents of our collection. The address.location field is being indexed as a geospatial field while the name field is being indexed as an autocomplete text field. No other fields within our document will be searchable based on this index.

By the end of the index creation, you should have something that looks like this:

MongoDB Atlas Search Autocomplete Geo Index

So, let’s go back to our code.

We know that our search results should be dependent on the text the user provides and the user’s location (as a latitude and longitude).

If we wanted to search just with text, our aggregation pipeline stage (query) would look like the following:

{
    "$search": {
        "index": "autocomplete",
        {
            "autocomplete": {
                "query": "apartment",
                "path": "name",
                "fuzzy": {
                    "maxEdits": 2,
                    "prefixLength": 3
                }
            }
        }
    }
}

The above stage says that we want to use the autocomplete index for our search and we want to use the autocomplete operator. We’re searching for “apartment” on the name field and we’re saying that we’re allowing typo tolerance, AKA fuzzy matching.

If we wanted to use Atlas Search to search within a geographic area, our aggregation pipeline stage would look like the following:

{
    "$search": {
        "index": "autocomplete",
        {
            "geoWithin": {
                "circle": {
                    "center": {
                        "type": "Point",
                        "coordinates": [-74.0060, 40.7128]
                    },
                    "radius": 10000
                },
                "path": "address.location"
            }
        }
    }
}

The above stage says once again we’re using the autocomplete index, but we’re using the geoWithin operator. We’re searching within a circular area where the center point is specified by a latitude and longitude. When working with GeoJSON like in the above code, the longitude is the first element in the coordinates array and the latitude is the second element. We’re also providing a radius to search around the center point.

We just created two possible aggregation pipeline stages. The problem is that we want to be efficient. We don’t want to search text using one stage and then apply a geo range on the results in a different stage. Instead we want to do our autocomplete and geoWithin operations within a single query.

We can do this with the compound operator.

To combine multiple operations, we can change our code and aggregation pipeline logic to look like the following:

app.post("/search", async (request, response, next) => {
    try {
        let result = await collection.aggregate([
            {
                "$search": {
                    "index": "autocomplete",
                    "compound": {
                        "must": [
                            {
                                "autocomplete": {
                                    "query": `${request.body.query}`,
                                    "path": "name",
                                    "fuzzy": {
                                        "maxEdits": 2,
                                        "prefixLength": 3
                                    }
                                }
                            },
                            {
                                "geoWithin": {
                                    "circle": {
                                        "center": {
                                            "type": "Point",
                                            "coordinates": [request.body.position.lng, request.body.position.lat]
                                        },
                                        "radius": 10000
                                    },
                                    "path": "address.location"
                                }
                            }
                        ]
                    }
                }
            }
        ]).toArray();
        response.send(result);
    } catch (e) {
        response.status(500).send({ message: e.message });
    }
});

Notice that we’re including a must array within the compound operator. You can learn more about each of the compound terms in the documentation, but the must operator defines which clauses must match to produce results.

To clear things up, we’re saying that the results must satisfy both the autocomplete and geoWithin operators.

Now, you can run the Node.js application and send the following payload to the endpoint using a POST request:

{
    "query": "apartment",
    "position": {
        "lng": -74.0060,
        "lat": 40.7128
    }
}

Given the data that is in the sample_airbnb dataset, we should end up with results around New York. However, the data we get back is likely more than we need. To limit the response, we can update our aggregation pipeline to not only search, but to project the fields we want in our response.

Modify the code to look like the following:

app.post("/search", async (request, response, next) => {
    try {
        let result = await collection.aggregate([
            {
                "$search": {
                    "index": "autocomplete",
                    "compound": {
                        "must": [
                            {
                                "autocomplete": {
                                    "query": `${request.body.query}`,
                                    "path": "name",
                                    "fuzzy": {
                                        "maxEdits": 2,
                                        "prefixLength": 3
                                    }
                                }
                            },
                            {
                                "geoWithin": {
                                    "circle": {
                                        "center": {
                                            "type": "Point",
                                            "coordinates": [request.body.position.lng, request.body.position.lat]
                                        },
                                        "radius": 10000
                                    },
                                    "path": "address.location"
                                }
                            }
                        ]
                    }
                }
            },
            {
                "$project": {
                    "name": 1,
                    "address": 1,
                    "score": { "$meta": "searchScore" }
                }
            }
        ]).toArray();
        response.send(result);
    } catch (e) {
        response.status(500).send({ message: e.message });
    }
});

To be clear about what was added to the above code, take note of the $project stage.

{
    "$project": {
        "name": 1,
        "address": 1,
        "score": { "$meta": "searchScore" }
    }
}

In the above $project stage, we are saying we only want the name and address fields returned. We are also interested in the scoring data that came back from our search. By default, the scoring data would not be present in our results. This data might be useful for determining the quality of the match.

With the back end out of the way, let’s focus on the front end.

Populating a Form Input with Autocomplete and JavaScript

To visualize the autocomplete search, we’re going to use jQuery with some basic HTML and JavaScript. The jQuery library will be responsible for sending our keystrokes to the API through an HTTP request.

Create another project directory that will represent the frontend application. Within that directory, create an index.html file with the following markup:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>
    <body>
        <div class="ui-widget">
            <label for="bnb">Bed and Breakfast [40.7128, -74.0060]:</label><br />
            <input id="bnb">
        </div>
        <script>
            $(document).ready(function () {
                // Autocomplete logic here...
            });
        </script>
    </body>
</html>

The markup above is boilerplate for getting started with jQuery — the exception being the <div> container that has the input field. The id of the input field is going to be important for when we work with jQuery.

So, let’s have a look at the autocomplete logic for the front end.

$(document).ready(function () {
    $("#bnb").autocomplete({
        source: async function (request, response) {
            let data = await fetch("http://localhost:3000/search", {
                    "method": "POST",
                    "headers": {
                        "content-type": "application/json"
                    },
                    "body": JSON.stringify({
                        "query": `${request.term}`,
                        "position": {
                            "lat": 40.7128,
                            "lng": -74.0060
                        }
                    })
                })
                .then(results => results.json())
                .then(results => results.map(result => {
                    return { label: result.name, value: result.name, id: result._id };
                }));
            response(data);
        },
        minLength: 2,
        select: function (event, ui) {
            // Further logic here...
        }
    });
});

In the above code, we are using the autocomplete function for jQuery on the bnb input element. The source of our data to show on the screen will come from our API endpoint. As characters are entered into the field, a POST request is made with the expected JSON payload. The results are then formatted to how jQuery expects them to be, in this case having a label, value, and id field within an object.

Because we want a narrow scope for this example, we won’t be looking at the logic for when an element is selected from the returned autocomplete results. However, just having the source field will allow us to visually show autocomplete results as we type them.

To run this example, you’ll need to serve the back end and front end separately. For the back end, navigate into the project directory with your command line and execute the following:

node main.js

The above command should start serving the API on port 3000. To serve the front end, you’ll either need Python or a compatible tool or package like serve, which is available through NPM.

If Python is available, you can execute the following from within your frontend project directory:

python -m SimpleHTTPServer

The above command will serve the front end on port 8000.

Of course, what I listed for serving your applications was meant for local development and testing. You’ll have to use your best judgment when deploying your applications to production.

Conclusion

You just saw how to use the compound operator for MongoDB Atlas Search to search based on text as well as within a geospatial area, in this case a circle. Why might this be valuable? Imagine needing to search for a hotel or restaurant near your location or within walking distance rather than returning all possible matches based on your text input. The compound operator lets you search for results only if they match the compounding terms provided.

To learn how to build more on Atlas Search, check out my other tutorials: Building an Autocomplete Form Element with Atlas Search and JavaScript and Visually Showing Atlas Search Highlights with JavaScript and HTML.

Questions or comments on this tutorial? Head to the MongoDB Community Forums and let’s chat!

This content first appeared on MongoDB.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.