================= Geospatial Search ================= You can query against :manual:`geospatial indexes ` in several ways via the Node.js driver, using :manual:`geospatial query operators ` . To create a 2dsphere index on a collection, pass a document containing the name of the field to be indexed with the value '2dsphere' to the ``createIndex()`` method. .. code-block:: js const { MongoClient } = require('mongodb'); // Connection URL const url = 'mongodb://localhost:27017'; // Create a new MongoClient const client = new MongoClient(url); async function main(client) { const collection = client.db('test').collection('restaurants'); const result = await collection.createIndex({ 'address.coord' : '2dsphere' }); console.log(result); } // Function to connect to the server and run your code async function run() { try { // Connect the client to the server await client.connect(); console.log('Connected successfully to server'); await main(client); } finally { // Ensures that the client will close when you finish/error await client.close(); } } // Runs your code run(); The following examples assume that a database called ``test`` has a collection called ``restaurants``\ , with a :manual:`2d sphere index ` index on the ``address.coord`` field. A `sample dataset `_ is available for download. $near ----- The :manual:`$near ` operator specifies a set of longitude-latitude coordinates and returns documents from nearest to farthest. .. code-block:: js async function main(client) { const collection = client.db('test').collection('restaurants'); const docs = await collection .find({ 'address.coord': { $near: { $geometry: { type: 'Point', coordinates: [ -73.9667, 40.78 ] }, $maxDistance: 1000 } } }) .toArray(); console.log('Found the following records'); console.log(docs); } The ``$maxDistance`` option specifies a maximum distance (in meters) from the given coordinates. For a complete list of ``$near`` options, see the :manual:`MongoDB manual ` . $geoWithin ---------- The :manual:`$geoWithin ` operator selects documents with geospatial data that exist within a specified shape. .. code-block:: js async function main(client) { const collection = client.db('test').collection('restaurants'); const docs = await collection .find({ 'address.coord': { $geoWithin: { $geometry: { type: 'Polygon', coordinates: [ [ [ -73, 40 ], [ -74, 41 ], [ -72, 39 ], [ -73, 40 ] ] ] } } } }) .toArray(); console.log('Found the following records'); console.log(docs); }