Use the MongoDB Search geo field type to index geographic points and shape coordinates. The indexed field must be a GeoJSON object. After you index a field as geo, you can query it using the geoShape and geoWithin operators.
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Retrieve your Service Account access token for the project.
Use your service account to generate an access token, which authenticates your requests to the Atlas Administration API. To learn how to generate an access token, see Make an API (Application Programming Interface) Request.
Make an API call.
Replace the following values in the curl command below. This command sends a POST request to your cluster to create a MongoDB Search index with the geo field type.
Replace {
ACCESS-TOKEN} with the output from the preceding stepReplace {
groupId} with the project ID of the project where you want to create the MongoDB Search indexReplace {
clusterName} with the name of the cluster where you want to create the MongoDB Search index
1 curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \ 2 --header "Accept: application/vnd.atlas.2025-03-12+json" \ 3 --header "Content-Type: application/json" \ 4 -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \ 5 -d '{ "collectionName": "<collection>", 6 "database": "<database>", 7 "name": "default", 8 "type": "search", 9 "definition": { 10 "mappings": { 11 "dynamic": true|false, 12 "fields": { 13 "<field-name>": { 14 "type": "geo", 15 "indexShapes": true|false 16 } 17 } 18 } 19 } 20 }'
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 curl --header "Authorization: Bearer ${ACCESS_TOKEN}" \ 2 --header "Accept: application/vnd.atlas.2025-03-12+json" \ 3 --header "Content-Type: application/json" \ 4 -X POST "https://cloud.mongodb.com/api/atlas/v2/groups/{groupId}/clusters/{clusterName}/search/indexes" \ 5 -d '{ "collectionName": "listingsAndReviews", 6 "database": "sample_airbnb", 7 "name": "default", 8 "type": "search", 9 "definition": { 10 "mappings": { 11 "dynamic": false, 12 "fields": { 13 "address": { 14 "type": "document", 15 "fields": { 16 "location": { 17 "type": "geo", 18 "indexShapes": true 19 } 20 } 21 } 22 } 23 } 24 } 25 }'
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Create a search-index.json configuration file and specify the geo type.
1 { 2 "name": "default", 3 "collectionName": "<collection>", 4 "database": "<database>", 5 "mappings": { 6 "dynamic": true|false, 7 "fields": { 8 "<field-name>": { 9 "type": "geo", 10 "indexShapes": true|false 11 } 12 } 13 } 14 }
Connect to the Atlas CLI
In your terminal, connect to your cluster from the Atlas CLI. To learn more, see Connect from the Atlas CLI.
Create a MongoDB Search index.
Run the atlas clusters search indexes create command in your terminal, replacing <clusterName> with the name of the cluster, and <path-to-file> with the path to the search-index.json file:
atlas clusters search indexes create --clusterName <cluster-name> --file <path-to-file>
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 { 2 "name": "default", 3 "collectionName": "listingsAndReviews", 4 "database": "sample_airbnb", 5 "mappings": { 6 "dynamic": false, 7 "fields": { 8 "address": { 9 "type": "document", 10 "fields": { 11 "location": { 12 "type": "geo", 13 "indexShapes": true 14 } 15 } 16 } 17 } 18 } 19 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Connect to your cluster using MongoDB Compass.
Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.
Create the MongoDB Search index.
Click the Indexes tab, then select Search Indexes.
Click Create Atlas Search Index to open the index creation dialog box.
Specify a name for the index.
Your MongoDB Search index is named
defaultby default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a differentindexoption in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.Specify the JSON MongoDB Search index definition.
1 { 2 "mappings": { 3 "dynamic": true|false, 4 "fields": { 5 "<field-name>": { 6 "type": "geo", 7 "indexShapes": true|false 8 } 9 } 10 } 11 } Click Create Search Index.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "address": { 6 "type": "document", 7 "fields": { 8 "location": { 9 "type": "geo", 10 "indexShapes": true 11 } 12 } 13 } 14 } 15 } 16 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Connect to the deployment by using mongosh.
In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from mongosh. For detailed instructions on how to connect, see Connect to a Deployment.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 db.listingsAndReviews.createSearchIndex( 2 "default", 3 { 4 "mappings": { 5 "dynamic": false, 6 "fields": { 7 "address": { 8 "fields" : { 9 "location": { 10 "type": "geo", 11 "indexShapes": true 12 } 13 } 14 } 15 } 16 }} 17 )
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Choose your preferred configuration method in the Atlas UI and then select the database and collection.
Click Refine Your Index to configure your index.
In the Field Mappings section, click Add Field Mapping to open the Add Field Mapping window.
Click Customized Configuration.
Select the field to index from the Field Name dropdown.
Note
You can't index fields that contain the dollar (
$) sign at the start of the field name.Click the Data Type dropdown and select Geo.
Configure the field properties for the
geotype. To learn more, see Field Properties.Click Add.
The following is the JSON syntax for the geo type. Replace the default index definition with the following. To learn more about the fields, see Field Properties.
{ "mappings": { "dynamic": true|false, "fields": { "<field-name>": { "type": "geo", "indexShapes": true|false } } } }
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
In the Add Field Mapping window, select address.location from the Field Name dropdown.
Click the Data Type dropdown and select Geo.
Modify the Geo Properties to set the value for Index Shapes to
true.Click Add.
Replace the default index definition with the following definition:
{ "mappings": { "dynamic": false, "fields": { "address": { "type": "document", "fields": { "location": { "type": "geo", "indexShapes": true } } } } } }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up the C project.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:
1 Create a new directory for the project 2 mkdir atlas-search-project && cd atlas-search-project
Add the C driver to your project by following the instructions in the MongoDB C Driver documentation.
Define the index.
Create a create_index.c file in your project directory, and copy and paste the following code into the file.
1 2 3 4 int main(int argc, char *argv[]) { 5 mongoc_client_t *client; 6 mongoc_collection_t *collection; 7 bson_error_t error; 8 bson_t cmd; 9 bson_t *index_definition; 10 bool success; 11 12 /* Initialize the MongoDB C Driver. */ 13 mongoc_init(); 14 15 /* Connect to your MongoDB deployment. */ 16 client = mongoc_client_new("<connection-string>"); 17 collection = mongoc_client_get_collection (client, "<database>", "<collection>"); 18 19 if (!client) { 20 fprintf(stderr, "Failed to create client.\n"); 21 return 1; 22 } 23 24 /* Create the MongoDB Search index definition for the geo field. */ 25 char *cmd_str = bson_strdup_printf ( 26 BSON_STR ({ 27 "createSearchIndexes": "%s", 28 "indexes": [{ 29 "name": "default", 30 "definition": { 31 "mappings": { 32 "dynamic": true|false, 33 "fields": { 34 "<field-name>": { 35 "type": "geo", 36 "indexShapes": true|false 37 } 38 } 39 } 40 } 41 }] 42 }), 43 "<collection>" 44 ); 45 bson_init_from_json (&cmd, cmd_str, -1, &error); 46 bson_free (cmd_str); 47 48 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 49 printf ("Index created!\n"); 50 } else { 51 fprintf (stderr, "Failed to create search index: %s", error.message); 52 } 53 54 /* Clean up. */ 55 bson_destroy (&cmd); 56 mongoc_collection_destroy (collection); 57 mongoc_client_destroy(client); 58 mongoc_cleanup(); 59 60 return 0; 61 }
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Set up a CMake application
To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:
1 cmake_minimum_required(VERSION 3.11) 2 project(atlas-search-index LANGUAGES C) 3 add_executable (index.out create_index.c) 4 find_package(mongoc <version> REQUIRED) 5 target_link_libraries(index.out mongoc::mongoc)
The preceding code performs the following actions:
Configures a C project.
Creates a
index.outexecutable for your application.Finds and requires the C driver. Replace the
<version>placeholder with your C driver version, such as2.0.0.Links the program to the
libmongoclibrary.
Note
In the sample CMakeLists.txt file, the mongoc::mongoc target points to either the static library or the shared library. The library type depends on which one is available and whichever type the user specifies in the MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE CMake configuration setting. If you don't set this value and both library types are available, mongoc::mongoc uses the static library.
You can use the mongoc::static target to explicitly use the static library or the mongoc::shared target to use the shared library.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 2 3 4 int main(int argc, char *argv[]) { 5 mongoc_client_t *client; 6 mongoc_collection_t *collection; 7 bson_error_t error; 8 bson_t cmd; 9 bson_t *index_definition; 10 bool success; 11 12 /* Initialize the MongoDB C Driver. */ 13 mongoc_init(); 14 15 /* Connect to your MongoDB deployment. */ 16 client = mongoc_client_new("<connection-string>"); 17 collection = mongoc_client_get_collection (client, "sample_airbnb", "listingsAndReviews"); 18 19 if (!client) { 20 fprintf(stderr, "Failed to create client.\n"); 21 return 1; 22 } 23 24 /* Create the MongoDB Search index definition for the geo field. */ 25 char *cmd_str = bson_strdup_printf ( 26 BSON_STR ({ 27 "createSearchIndexes": "%s", 28 "indexes": [{ 29 "name": "default", 30 "definition": { 31 "mappings": { 32 "dynamic": false, 33 "fields": { 34 "address": { 35 "type": "document", 36 "fields": { 37 "location": { 38 "type": "geo", 39 "indexShapes": true 40 } 41 } 42 } 43 } 44 } 45 } 46 }] 47 }), 48 "listingsAndReviews" 49 ); 50 bson_init_from_json (&cmd, cmd_str, -1, &error); 51 bson_free (cmd_str); 52 53 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 54 printf ("Index created!\n"); 55 } else { 56 fprintf (stderr, "Failed to create search index: %s", error.message); 57 } 58 59 /* Clean up. */ 60 bson_destroy (&cmd); 61 mongoc_collection_destroy (collection); 62 mongoc_client_destroy(client); 63 mongoc_cleanup(); 64 65 return 0; 66 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up and initialize the .NET/C# project.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:
Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project dotnet new console Add the MongoDB .NET/C# Driver to your project dotnet add package MongoDB.Driver
For more detailed installation instructions, see the MongoDB .NET/C# Driver documentation.
Define the index.
Paste the following code into the Program.cs file.
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // Replace the connection string with your MongoDB deployment's connection string 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("<database>"); 10 var collection = db.GetCollection<BsonDocument>("<collection>"); 11 12 // Create the MongoDB Search index definition for the geo field 13 var index = new CreateSearchIndexModel( 14 "default", new BsonDocument 15 { 16 { "mappings", new BsonDocument 17 { 18 { "dynamic", true|false }, 19 { "fields", new BsonDocument 20 { 21 { "<field-name>", new BsonDocument 22 { 23 { "type", "geo" }, 24 { "indexShapes", true|false } 25 } 26 } 27 } 28 } 29 } 30 } 31 }); 32 33 var result = collection.SearchIndexes.CreateOne(index); 34 Console.WriteLine($"New index name: {result}");
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // Replace the connection string with your MongoDB deployment's connection string 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("sample_airbnb"); 10 var collection = db.GetCollection<BsonDocument>("listingsAndReviews"); 11 12 // Create the MongoDB Search index definition for the geo field 13 var index = new CreateSearchIndexModel( 14 "default", new BsonDocument 15 { 16 { "mappings", new BsonDocument 17 { 18 { "dynamic", false }, 19 { "fields", new BsonDocument 20 { 21 { "address", new BsonDocument 22 { 23 { "type", "document" }, 24 { "fields", new BsonDocument 25 { 26 { "location", new BsonDocument 27 { 28 { "type", "geo" }, 29 { "indexShapes", true } 30 } 31 } 32 } 33 } 34 } 35 } 36 } 37 } 38 } 39 } 40 }); 41 42 var result = collection.SearchIndexes.CreateOne(index); 43 Console.WriteLine($"New index name: {result}");
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up the C++ project.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:
Create a new directory for the project mkdir atlas-search-project && cd atlas-search-project
For more detailed installation instructions, see the MongoDB C++ Driver documentation.
Define the index.
Create a CreateIndex.cpp file in your project directory, and copy and paste the following code into the file.
1 2 3 4 5 6 7 8 9 using bsoncxx::builder::basic::kvp; 10 using bsoncxx::builder::basic::make_document; 11 12 int main() { 13 // Initialize the MongoDB C++ driver 14 mongocxx::instance instance{}; 15 16 // Connect to your MongoDB deployment 17 mongocxx::uri uri("<connection-string>"); 18 mongocxx::client client(uri); 19 20 auto db = client["<database>"]; 21 auto collection = db["<collection>"]; 22 auto siv = collection.search_indexes(); 23 24 // Create the MongoDB Search index definition for the geo field 25 auto name = "default"; 26 auto definition = make_document( 27 kvp("mappings", make_document( 28 kvp("dynamic", true|false), 29 kvp("fields", make_document( 30 kvp("<field-name>", make_document( 31 kvp("type", "geo"), 32 kvp("indexShapes", true|false) 33 )) 34 )) 35 )) 36 ); 37 auto model = mongocxx::search_index_model(name, definition.view()); 38 39 try { 40 // Execute the command to create the index 41 auto result = siv.create_one(model); 42 std::cout << "New index name: " << result << std::endl; 43 } catch (const std::exception& e) { 44 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl; 45 } 46 47 }
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Create the index.
c++ --std=c++17 CreateIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out ./app.out
New index name: default
Tip
MacOS Error
MacOS users might see the following error after running the preceding commands:
dyld[54430]: Library not loaded: @rpath/libmongocxx._noabi.dylib
To resolve this error, use the -Wl,``-rpath`` linker option to set the @rpath, as shown in the following code:
c++ --std=c++17 CreateIndex.cpp -Wl,-rpath,/usr/local/lib/ $(pkg-config --cflags --libs libmongocxx) -o ./app.out ./app.out
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 2 3 4 5 6 7 8 9 using bsoncxx::builder::basic::kvp; 10 using bsoncxx::builder::basic::make_document; 11 12 int main() { 13 // Initialize the MongoDB C++ driver 14 mongocxx::instance instance{}; 15 16 // Connect to your MongoDB deployment 17 mongocxx::uri uri("<connection-string>"); 18 mongocxx::client client(uri); 19 20 auto db = client["sample_airbnb"]; 21 auto collection = db["listingsAndReviews"]; 22 auto siv = collection.search_indexes(); 23 24 // Create the MongoDB Search index definition for the geo field 25 auto name = "default"; 26 auto definition = make_document( 27 kvp("mappings", make_document( 28 kvp("dynamic", false), 29 kvp("fields", make_document( 30 kvp("address", make_document( 31 kvp("type", "document"), 32 kvp("fields", make_document( 33 kvp("location", make_document( 34 kvp("type", "geo"), 35 kvp("indexShapes", true) 36 )) 37 )) 38 )) 39 )) 40 )) 41 ); 42 auto model = mongocxx::search_index_model(name, definition.view()); 43 44 try { 45 // Execute the command to create the index 46 auto result = siv.create_one(model); 47 std::cout << "New index name: " << result << std::endl; 48 } catch (const std::exception& e) { 49 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl; 50 } 51 52 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up and initialize the Go module.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:
Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project go mod init atlas-search-project Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo
For more detailed installation instructions, see the MongoDB Go Driver documentation.
Define the index.
Create a create_index.go file in your project directory, and copy and paste the following code into the file.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 8 "go.mongodb.org/mongo-driver/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 func main() { 14 ctx := context.Background() 15 uri := "mongodb+srv://<username>:<password>@<cluster-url>/myDatabase?retryWrites=true&w=majority" 16 client, err := mongo.Connect(options.Client(). 17 ApplyURI(uri)) 18 if err != nil { 19 panic(err) 20 } 21 22 defer func() { 23 if err := client.Disconnect(context.TODO()); err != nil { 24 panic(err) 25 } 26 }() 27 28 coll := client.Database("<database>").Collection("<collection>") 29 const indexName = "default" 30 opts := options.SearchIndexes().SetName(indexName).SetType("search") 31 32 // Define the MongoDB Search index for the geo field 33 searchIndexModel := mongo.SearchIndexModel{ 34 Definition: bson.D{ 35 {"mappings", bson.D{ 36 {"dynamic", true | false}, 37 {"fields", bson.D{ 38 {"<field-name>", bson.D{ 39 {"type", "geo"}, 40 {"indexShapes", true | false}, 41 }}, 42 }}, 43 }}, 44 }, 45 Options: opts, 46 } 47 48 // Create the index 49 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 50 if err != nil { 51 log.Fatalf("Failed to create the Atlas Search index: %v", err) 52 } 53 54 fmt.Println("Name of index created: " + searchIndexName) 55 }
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
Your connection string should use the following format:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 8 "go.mongodb.org/mongo-driver/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 func main() { 14 ctx := context.Background() 15 uri := "mongodb+srv://<username>:<password>@<cluster-url>/myDatabase?retryWrites=true&w=majority" 16 client, err := mongo.Connect(options.Client(). 17 ApplyURI(uri)) 18 if err != nil { 19 panic(err) 20 } 21 22 defer func() { 23 if err := client.Disconnect(context.TODO()); err != nil { 24 panic(err) 25 } 26 }() 27 28 coll := client.Database("sample_airbnb").Collection("listingsAndReviews") 29 const indexName = "default" 30 opts := options.SearchIndexes().SetName(indexName).SetType("search") 31 32 // Define the MongoDB Search index for the geo field 33 searchIndexModel := mongo.SearchIndexModel{ 34 Definition: bson.D{ 35 {"mappings", bson.D{ 36 {"dynamic", false}, 37 {"fields", bson.D{ 38 {"address", bson.D{ 39 {"type", "document"}, 40 {"fields", bson.D{ 41 {"location", bson.D{ 42 {"type", "geo"}, 43 {"indexShapes", true}, 44 }}, 45 }}, 46 }}, 47 }}, 48 }}, 49 }, 50 Options: opts, 51 } 52 53 // Create the index 54 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 55 if err != nil { 56 log.Fatalf("Failed to create the Atlas Search index: %v", err) 57 } 58 59 fmt.Println("Name of index created: " + searchIndexName) 60 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up your Java project with the MongoDB Java driver.
In your IDE, create a new Maven or Gradle project. Add the Bill of Materials (BOM) for MongoDB JVM artifacts to your project to organize dependency versions. The BOM simplifies dependency management by ensuring that you maintain consistent and compatible versions of dependencies, such as between the Java driver and the core driver library. Use the BOM to avoid version conflicts and simplify upgrades.
Select from the following Maven and Gradle tabs to view instructions for adding the BOM for each dependency manager:
Add the following code to the dependencyManagement list in your pom.xml file:
<dependencyManagement> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-bom</artifactId> <version>5.5.1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
Add the following code to dependencies list in your build.gradle file:
dependencies { implementation(platform("org.mongodb:mongodb-driver-bom:5.5.1")) }
To view a list of dependencies that the BOM manages, see the mongodb-driver-bom dependency listing on the Maven Repository website.
After adding the BOM, select from the following Maven and Gradle tabs to view instructions for adding the MongoDB Java Sync Driver as a dependency in your project:
Add the following code to the dependencies array in your Maven project's pom.xml file:
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.11.1</version> </dependency> </dependencies>
Add the following to the dependencies array in your Gradle project's build.gradle file:
dependencies { // MongoDB Java Sync Driver v4.11.0 or later implementation 'org.mongodb:mongodb-driver-sync' }
Run your package manager to install the dependencies to your project.
For more detailed installation instructions and version compatibility, see the MongoDB Java Driver documentation.
Define the index.
In your project's base package directory, create a CreateIndex.java file and copy and paste the following code into this file.
1 import com.mongodb.client.*; 2 import org.bson.Document; 3 4 public class CreateIndex { 5 public static void main(String[] args) { 6 // Replace the connection string with your MongoDB deployment's connection string 7 String connectionString = "<connection-string>"; 8 9 try (MongoClient mongoClient = MongoClients.create(connectionString)) { 10 MongoDatabase database = mongoClient.getDatabase("<database>"); 11 MongoCollection<Document> collection = database.getCollection("<collection>"); 12 String indexName = "default"; 13 14 // Create the MongoDB Search index definition for the geo field 15 Document searchIdx = new Document( 16 "mappings", 17 new Document("dynamic", true|false) 18 .append("fields", 19 new Document("<field-name>", 20 new Document("type", "geo") 21 .append("indexShapes", true|false) 22 ))); 23 collection.createSearchIndex(indexName, searchIdx); 24 System.out.println("New index name: " + indexName); 25 } catch (Exception e) { 26 System.err.println("Error creating Atlas Search index: " + e.getMessage()); 27 } 28 } 29 }
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 import com.mongodb.client.*; 2 import org.bson.Document; 3 4 public class CreateIndex { 5 public static void main(String[] args) { 6 // Replace the connection string with your MongoDB deployment's connection string 7 String connectionString = "<connection-string>"; 8 9 try (MongoClient mongoClient = MongoClients.create(connectionString)) { 10 MongoDatabase database = mongoClient.getDatabase("sample_airbnb"); 11 MongoCollection<Document> collection = database.getCollection("listingsAndReviews"); 12 String indexName = "default"; 13 14 // Create the MongoDB Search index definition for the geo field 15 Document searchIdx = new Document( 16 "mappings", 17 new Document("dynamic", false) 18 .append("fields", 19 new Document("address", 20 new Document("type", "document") 21 .append("fields", new Document("location", 22 new Document("type", "geo") 23 .append("indexShapes", true))))) 24 ); 25 collection.createSearchIndex(indexName, searchIdx); 26 System.out.println("New index name: " + indexName); 27 } catch (Exception e) { 28 System.err.println("Error creating Atlas Search index: " + e.getMessage()); 29 } 30 } 31 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Initialize your Node.js project.
Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project npm init -y Add the MongoDB Node.js Driver to your project npm install mongodb
For detailed installation instructions, see the MongoDB Node Driver documentation.
Define the index.
Create a create-index.js file in your project directory, and copy and paste the following code into the file.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the connection string with your MongoDB deployment's connection string 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("<database>"); 11 const collection = database.collection("<collection>"); 12 13 // Create the MongoDB Search index definition for the geo field 14 const index = { 15 name: "default", 16 definition: { 17 "mappings": { 18 "dynamic": true|false, 19 "fields": { 20 "<field-name>": { 21 "type": "geo", 22 "indexShapes": true|false 23 } 24 } 25 } 26 } 27 } 28 29 // Create the index 30 const result = await collection.createSearchIndex(index); 31 console.log("New index name: " + result); 32 } finally { 33 await client.close(); 34 } 35 } 36 37 run().catch(console.dir);
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the connection string with your MongoDB deployment's connection string 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("sample_airbnb"); 11 const collection = database.collection("listingsAndReviews"); 12 13 // Create the MongoDB Search index definition for the geo field 14 const index = { 15 name: "default", 16 definition: { 17 "mappings": { 18 "dynamic": false, 19 "fields": { 20 "address": { 21 "type": "document", 22 "fields": { 23 "location": { 24 "type": "geo", 25 "indexShapes": true 26 } 27 } 28 } 29 } 30 } 31 } 32 } 33 34 // Create the index 35 const result = await collection.createSearchIndex(index); 36 console.log("New index name: " + result); 37 } finally { 38 await client.close(); 39 } 40 } 41 42 run().catch(console.dir);
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up the Python project.
Create a new directory for the project mkdir atlas-search-project && cd atlas-search-project Install PyMongo pip install pymongo
For detailed installation instructions, see the MongoDB PyMongo Driver documentation.
Define the index.
Create a create_index.py file in your project directory, and copy and paste the following code into the file.
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # Connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 database = client["<database>"] 9 collection = database["<collection>"] 10 11 # Create the MongoDB Search index definition for the geo field 12 search_index_model = SearchIndexModel( 13 definition={ 14 "mappings": { 15 "dynamic": true|false, 16 "fields": { 17 "<field-name>":{ 18 "type": "geo", 19 "indexShapes": true|false 20 } 21 } 22 }, 23 }, 24 name="default", 25 ) 26 27 # Create the index 28 result = collection.create_search_index(model=search_index_model) 29 print(f"New index name: {result}")
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # Connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 database = client["sample_airbnb"] 9 collection = database["listingsAndReviews"] 10 11 # Create the MongoDB Search index definition for the geo field 12 search_index_model = SearchIndexModel( 13 definition={ 14 "mappings": { 15 "dynamic": false, 16 "fields": { 17 "address": { 18 "type": "document", 19 "fields": { 20 "location": { 21 "type": "geo", 22 "indexShapes": true 23 } 24 } 25 } 26 } 27 }, 28 }, 29 name="default", 30 ) 31 32 # Create the index 33 result = collection.create_search_index(model=search_index_model) 34 print(f"New index name: {result}")
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Create a search-index.json configuration file and specify the geo type.
1 { 2 "name": "default", 3 "collectionName": "<collection>", 4 "database": "<database>", 5 "mappings": { 6 "dynamic": true|false, 7 "fields": { 8 "<field-name>": { 9 "type": "geo", 10 "indexShapes": true|false 11 } 12 } 13 } 14 }
Connect to the Atlas CLI
In your terminal, connect to your local deployment from the Atlas CLI. To learn more, see Connect from the Atlas CLI.
Create a MongoDB Search index.
Run the atlas deployments search indexes create command in your terminal, replacing <path-to-file> with the path to the search-index.json file:
atlas deployments search indexes create --file <path-to-file>
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 { 2 "name": "default", 3 "collectionName": "listingsAndReviews", 4 "database": "sample_airbnb", 5 "mappings": { 6 "dynamic": false, 7 "fields": { 8 "address": { 9 "type": "document", 10 "fields": { 11 "location": { 12 "type": "geo", 13 "indexShapes": true 14 } 15 } 16 } 17 } 18 } 19 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Connect to your cluster using MongoDB Compass.
Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.
Create the MongoDB Search index.
Click the Indexes tab, then select Search Indexes.
Click Create Atlas Search Index to open the index creation dialog box.
Specify a name for the index.
Your MongoDB Search index is named
defaultby default. If you keep this name, then your index will be the default Search index for any MongoDB Search query that does not specify a differentindexoption in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.Specify the JSON MongoDB Search index definition.
1 { 2 "mappings": { 3 "dynamic": true|false, 4 "fields": { 5 "<field-name>": { 6 "type": "geo", 7 "indexShapes": true|false 8 } 9 } 10 } 11 } Click Create Search Index.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 { 2 "mappings": { 3 "dynamic": false, 4 "fields": { 5 "address": { 6 "type": "document", 7 "fields": { 8 "location": { 9 "type": "geo", 10 "indexShapes": true 11 } 12 } 13 } 14 } 15 } 16 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Connect to the deployment by using mongosh.
In your terminal, connect to your Atlas cloud-hosted deployment or local deployment from mongosh. For detailed instructions on how to connect, see Connect to a Deployment.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 db.listingsAndReviews.createSearchIndex( 2 "default", 3 { 4 "mappings": { 5 "dynamic": false, 6 "fields": { 7 "address": { 8 "fields" : { 9 "location": { 10 "type": "geo", 11 "indexShapes": true 12 } 13 } 14 } 15 } 16 }} 17 )
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up the C project.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:
1 Create a new directory for the project 2 mkdir atlas-search-project && cd atlas-search-project
Add the C driver to your project by following the instructions in the MongoDB C Driver documentation.
Define the index.
Create a create_index.c file in your project directory, and copy and paste the following code into the file.
1 2 3 4 int main(int argc, char *argv[]) { 5 mongoc_client_t *client; 6 mongoc_collection_t *collection; 7 bson_error_t error; 8 bson_t cmd; 9 bson_t *index_definition; 10 bool success; 11 12 /* Initialize the MongoDB C Driver. */ 13 mongoc_init(); 14 15 /* Connect to your MongoDB deployment. */ 16 client = mongoc_client_new("<connection-string>"); 17 collection = mongoc_client_get_collection (client, "<database>", "<collection>"); 18 19 if (!client) { 20 fprintf(stderr, "Failed to create client.\n"); 21 return 1; 22 } 23 24 /* Create the MongoDB Search index definition for the geo field. */ 25 char *cmd_str = bson_strdup_printf ( 26 BSON_STR ({ 27 "createSearchIndexes": "%s", 28 "indexes": [{ 29 "name": "default", 30 "definition": { 31 "mappings": { 32 "dynamic": true|false, 33 "fields": { 34 "<field-name>": { 35 "type": "geo", 36 "indexShapes": true|false 37 } 38 } 39 } 40 } 41 }] 42 }), 43 "<collection>" 44 ); 45 bson_init_from_json (&cmd, cmd_str, -1, &error); 46 bson_free (cmd_str); 47 48 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 49 printf ("Index created!\n"); 50 } else { 51 fprintf (stderr, "Failed to create search index: %s", error.message); 52 } 53 54 /* Clean up. */ 55 bson_destroy (&cmd); 56 mongoc_collection_destroy (collection); 57 mongoc_client_destroy(client); 58 mongoc_cleanup(); 59 60 return 0; 61 }
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Set up a CMake application
To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:
1 cmake_minimum_required(VERSION 3.11) 2 project(atlas-search-index LANGUAGES C) 3 add_executable (index.out create_index.c) 4 find_package(mongoc <version> REQUIRED) 5 target_link_libraries(index.out mongoc::mongoc)
The preceding code performs the following actions:
Configures a C project.
Creates a
index.outexecutable for your application.Finds and requires the C driver. Replace the
<version>placeholder with your C driver version, such as2.0.0.Links the program to the
libmongoclibrary.
Note
In the sample CMakeLists.txt file, the mongoc::mongoc target points to either the static library or the shared library. The library type depends on which one is available and whichever type the user specifies in the MONGOC_DEFAULT_IMPORTED_LIBRARY_TYPE CMake configuration setting. If you don't set this value and both library types are available, mongoc::mongoc uses the static library.
You can use the mongoc::static target to explicitly use the static library or the mongoc::shared target to use the shared library.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 2 3 4 int main(int argc, char *argv[]) { 5 mongoc_client_t *client; 6 mongoc_collection_t *collection; 7 bson_error_t error; 8 bson_t cmd; 9 bson_t *index_definition; 10 bool success; 11 12 /* Initialize the MongoDB C Driver. */ 13 mongoc_init(); 14 15 /* Connect to your MongoDB deployment. */ 16 client = mongoc_client_new("<connection-string>"); 17 collection = mongoc_client_get_collection (client, "sample_airbnb", "listingsAndReviews"); 18 19 if (!client) { 20 fprintf(stderr, "Failed to create client.\n"); 21 return 1; 22 } 23 24 /* Create the MongoDB Search index definition for the geo field. */ 25 char *cmd_str = bson_strdup_printf ( 26 BSON_STR ({ 27 "createSearchIndexes": "%s", 28 "indexes": [{ 29 "name": "default", 30 "definition": { 31 "mappings": { 32 "dynamic": false, 33 "fields": { 34 "address": { 35 "type": "document", 36 "fields": { 37 "location": { 38 "type": "geo", 39 "indexShapes": true 40 } 41 } 42 } 43 } 44 } 45 } 46 }] 47 }), 48 "listingsAndReviews" 49 ); 50 bson_init_from_json (&cmd, cmd_str, -1, &error); 51 bson_free (cmd_str); 52 53 if (mongoc_collection_command_simple (collection, &cmd, NULL, NULL, &error)) { 54 printf ("Index created!\n"); 55 } else { 56 fprintf (stderr, "Failed to create search index: %s", error.message); 57 } 58 59 /* Clean up. */ 60 bson_destroy (&cmd); 61 mongoc_collection_destroy (collection); 62 mongoc_client_destroy(client); 63 mongoc_cleanup(); 64 65 return 0; 66 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up and initialize the .NET/C# project.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:
Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project dotnet new console Add the MongoDB .NET/C# Driver to your project dotnet add package MongoDB.Driver
For more detailed installation instructions, see the MongoDB .NET/C# Driver documentation.
Define the index.
Paste the following code into the Program.cs file.
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // Replace the connection string with your MongoDB deployment's connection string 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("<database>"); 10 var collection = db.GetCollection<BsonDocument>("<collection>"); 11 12 // Create the MongoDB Search index definition for the geo field 13 var index = new CreateSearchIndexModel( 14 "default", new BsonDocument 15 { 16 { "mappings", new BsonDocument 17 { 18 { "dynamic", true|false }, 19 { "fields", new BsonDocument 20 { 21 { "<field-name>", new BsonDocument 22 { 23 { "type", "geo" }, 24 { "indexShapes", true|false } 25 } 26 } 27 } 28 } 29 } 30 } 31 }); 32 33 var result = collection.SearchIndexes.CreateOne(index); 34 Console.WriteLine($"New index name: {result}");
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 using MongoDB.Bson; 2 using MongoDB.Driver; 3 4 // Replace the connection string with your MongoDB deployment's connection string 5 var uri = "<connection-string>"; 6 7 var client = new MongoClient(uri); 8 9 var db = client.GetDatabase("sample_airbnb"); 10 var collection = db.GetCollection<BsonDocument>("listingsAndReviews"); 11 12 // Create the MongoDB Search index definition for the geo field 13 var index = new CreateSearchIndexModel( 14 "default", new BsonDocument 15 { 16 { "mappings", new BsonDocument 17 { 18 { "dynamic", false }, 19 { "fields", new BsonDocument 20 { 21 { "address", new BsonDocument 22 { 23 { "type", "document" }, 24 { "fields", new BsonDocument 25 { 26 { "location", new BsonDocument 27 { 28 { "type", "geo" }, 29 { "indexShapes", true } 30 } 31 } 32 } 33 } 34 } 35 } 36 } 37 } 38 } 39 } 40 }); 41 42 var result = collection.SearchIndexes.CreateOne(index); 43 Console.WriteLine($"New index name: {result}");
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up the C++ project.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project for this project:
Create a new directory for the project mkdir atlas-search-project && cd atlas-search-project
For more detailed installation instructions, see the MongoDB C++ Driver documentation.
Define the index.
Create a CreateIndex.cpp file in your project directory, and copy and paste the following code into the file.
1 2 3 4 5 6 7 8 9 using bsoncxx::builder::basic::kvp; 10 using bsoncxx::builder::basic::make_document; 11 12 int main() { 13 // Initialize the MongoDB C++ driver 14 mongocxx::instance instance{}; 15 16 // Connect to your MongoDB deployment 17 mongocxx::uri uri("<connection-string>"); 18 mongocxx::client client(uri); 19 20 auto db = client["<database>"]; 21 auto collection = db["<collection>"]; 22 auto siv = collection.search_indexes(); 23 24 // Create the MongoDB Search index definition for the geo field 25 auto name = "default"; 26 auto definition = make_document( 27 kvp("mappings", make_document( 28 kvp("dynamic", true|false), 29 kvp("fields", make_document( 30 kvp("<field-name>", make_document( 31 kvp("type", "geo"), 32 kvp("indexShapes", true|false) 33 )) 34 )) 35 )) 36 ); 37 auto model = mongocxx::search_index_model(name, definition.view()); 38 39 try { 40 // Execute the command to create the index 41 auto result = siv.create_one(model); 42 std::cout << "New index name: " << result << std::endl; 43 } catch (const std::exception& e) { 44 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl; 45 } 46 47 }
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Create the index.
c++ --std=c++17 CreateIndex.cpp $(pkg-config --cflags --libs libmongocxx) -o ./app.out ./app.out
New index name: default
Tip
MacOS Error
MacOS users might see the following error after running the preceding commands:
dyld[54430]: Library not loaded: @rpath/libmongocxx._noabi.dylib
To resolve this error, use the -Wl,``-rpath`` linker option to set the @rpath, as shown in the following code:
c++ --std=c++17 CreateIndex.cpp -Wl,-rpath,/usr/local/lib/ $(pkg-config --cflags --libs libmongocxx) -o ./app.out ./app.out
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 2 3 4 5 6 7 8 9 using bsoncxx::builder::basic::kvp; 10 using bsoncxx::builder::basic::make_document; 11 12 int main() { 13 // Initialize the MongoDB C++ driver 14 mongocxx::instance instance{}; 15 16 // Connect to your MongoDB deployment 17 mongocxx::uri uri("<connection-string>"); 18 mongocxx::client client(uri); 19 20 auto db = client["sample_airbnb"]; 21 auto collection = db["listingsAndReviews"]; 22 auto siv = collection.search_indexes(); 23 24 // Create the MongoDB Search index definition for the geo field 25 auto name = "default"; 26 auto definition = make_document( 27 kvp("mappings", make_document( 28 kvp("dynamic", false), 29 kvp("fields", make_document( 30 kvp("address", make_document( 31 kvp("type", "document"), 32 kvp("fields", make_document( 33 kvp("location", make_document( 34 kvp("type", "geo"), 35 kvp("indexShapes", true) 36 )) 37 )) 38 )) 39 )) 40 )) 41 ); 42 auto model = mongocxx::search_index_model(name, definition.view()); 43 44 try { 45 // Execute the command to create the index 46 auto result = siv.create_one(model); 47 std::cout << "New index name: " << result << std::endl; 48 } catch (const std::exception& e) { 49 std::cerr << "Error creating Atlas Search index: " << e.what() << std::endl; 50 } 51 52 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up and initialize the Go module.
In your terminal, navigate to where you want to create your application, then run the following command to create a directory called atlas-search-project and initialize your project in that directory:
Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project go mod init atlas-search-project Add the MongoDB Go Driver to your project go get go.mongodb.org/mongo-driver/v2/mongo
For more detailed installation instructions, see the MongoDB Go Driver documentation.
Define the index.
Create a create_index.go file in your project directory, and copy and paste the following code into the file.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 8 "go.mongodb.org/mongo-driver/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 func main() { 14 ctx := context.Background() 15 uri := "mongodb+srv://<username>:<password>@<cluster-url>/myDatabase?retryWrites=true&w=majority" 16 client, err := mongo.Connect(options.Client(). 17 ApplyURI(uri)) 18 if err != nil { 19 panic(err) 20 } 21 22 defer func() { 23 if err := client.Disconnect(context.TODO()); err != nil { 24 panic(err) 25 } 26 }() 27 28 coll := client.Database("<database>").Collection("<collection>") 29 const indexName = "default" 30 opts := options.SearchIndexes().SetName(indexName).SetType("search") 31 32 // Define the MongoDB Search index for the geo field 33 searchIndexModel := mongo.SearchIndexModel{ 34 Definition: bson.D{ 35 {"mappings", bson.D{ 36 {"dynamic", true | false}, 37 {"fields", bson.D{ 38 {"<field-name>", bson.D{ 39 {"type", "geo"}, 40 {"indexShapes", true | false}, 41 }}, 42 }}, 43 }}, 44 }, 45 Options: opts, 46 } 47 48 // Create the index 49 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 50 if err != nil { 51 log.Fatalf("Failed to create the Atlas Search index: %v", err) 52 } 53 54 fmt.Println("Name of index created: " + searchIndexName) 55 }
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
Your connection string should use the following format:
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
IMPORTANT: Ensure that your connection string includes your database user's credentials. To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 package main 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 8 "go.mongodb.org/mongo-driver/v2/bson" 9 "go.mongodb.org/mongo-driver/v2/mongo" 10 "go.mongodb.org/mongo-driver/v2/mongo/options" 11 ) 12 13 func main() { 14 ctx := context.Background() 15 uri := "mongodb+srv://<username>:<password>@<cluster-url>/myDatabase?retryWrites=true&w=majority" 16 client, err := mongo.Connect(options.Client(). 17 ApplyURI(uri)) 18 if err != nil { 19 panic(err) 20 } 21 22 defer func() { 23 if err := client.Disconnect(context.TODO()); err != nil { 24 panic(err) 25 } 26 }() 27 28 coll := client.Database("sample_airbnb").Collection("listingsAndReviews") 29 const indexName = "default" 30 opts := options.SearchIndexes().SetName(indexName).SetType("search") 31 32 // Define the MongoDB Search index for the geo field 33 searchIndexModel := mongo.SearchIndexModel{ 34 Definition: bson.D{ 35 {"mappings", bson.D{ 36 {"dynamic", false}, 37 {"fields", bson.D{ 38 {"address", bson.D{ 39 {"type", "document"}, 40 {"fields", bson.D{ 41 {"location", bson.D{ 42 {"type", "geo"}, 43 {"indexShapes", true}, 44 }}, 45 }}, 46 }}, 47 }}, 48 }}, 49 }, 50 Options: opts, 51 } 52 53 // Create the index 54 searchIndexName, err := coll.SearchIndexes().CreateOne(ctx, searchIndexModel) 55 if err != nil { 56 log.Fatalf("Failed to create the Atlas Search index: %v", err) 57 } 58 59 fmt.Println("Name of index created: " + searchIndexName) 60 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up your Java project with the MongoDB Java driver.
In your IDE, create a new Maven or Gradle project. Add the Bill of Materials (BOM) for MongoDB JVM artifacts to your project to organize dependency versions. The BOM simplifies dependency management by ensuring that you maintain consistent and compatible versions of dependencies, such as between the Java driver and the core driver library. Use the BOM to avoid version conflicts and simplify upgrades.
Select from the following Maven and Gradle tabs to view instructions for adding the BOM for each dependency manager:
Add the following code to the dependencyManagement list in your pom.xml file:
<dependencyManagement> <dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-bom</artifactId> <version>5.5.1</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
Add the following code to dependencies list in your build.gradle file:
dependencies { implementation(platform("org.mongodb:mongodb-driver-bom:5.5.1")) }
To view a list of dependencies that the BOM manages, see the mongodb-driver-bom dependency listing on the Maven Repository website.
After adding the BOM, select from the following Maven and Gradle tabs to view instructions for adding the MongoDB Java Sync Driver as a dependency in your project:
Add the following code to the dependencies array in your Maven project's pom.xml file:
<dependencies> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.11.1</version> </dependency> </dependencies>
Add the following to the dependencies array in your Gradle project's build.gradle file:
dependencies { // MongoDB Java Sync Driver v4.11.0 or later implementation 'org.mongodb:mongodb-driver-sync' }
Run your package manager to install the dependencies to your project.
For more detailed installation instructions and version compatibility, see the MongoDB Java Driver documentation.
Define the index.
In your project's base package directory, create a CreateIndex.java file and copy and paste the following code into this file.
1 import com.mongodb.client.*; 2 import org.bson.Document; 3 4 public class CreateIndex { 5 public static void main(String[] args) { 6 // Replace the connection string with your MongoDB deployment's connection string 7 String connectionString = "<connection-string>"; 8 9 try (MongoClient mongoClient = MongoClients.create(connectionString)) { 10 MongoDatabase database = mongoClient.getDatabase("<database>"); 11 MongoCollection<Document> collection = database.getCollection("<collection>"); 12 String indexName = "default"; 13 14 // Create the MongoDB Search index definition for the geo field 15 Document searchIdx = new Document( 16 "mappings", 17 new Document("dynamic", true|false) 18 .append("fields", 19 new Document("<field-name>", 20 new Document("type", "geo") 21 .append("indexShapes", true|false) 22 ))); 23 collection.createSearchIndex(indexName, searchIdx); 24 System.out.println("New index name: " + indexName); 25 } catch (Exception e) { 26 System.err.println("Error creating Atlas Search index: " + e.getMessage()); 27 } 28 } 29 }
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 import com.mongodb.client.*; 2 import org.bson.Document; 3 4 public class CreateIndex { 5 public static void main(String[] args) { 6 // Replace the connection string with your MongoDB deployment's connection string 7 String connectionString = "<connection-string>"; 8 9 try (MongoClient mongoClient = MongoClients.create(connectionString)) { 10 MongoDatabase database = mongoClient.getDatabase("sample_airbnb"); 11 MongoCollection<Document> collection = database.getCollection("listingsAndReviews"); 12 String indexName = "default"; 13 14 // Create the MongoDB Search index definition for the geo field 15 Document searchIdx = new Document( 16 "mappings", 17 new Document("dynamic", false) 18 .append("fields", 19 new Document("address", 20 new Document("type", "document") 21 .append("fields", new Document("location", 22 new Document("type", "geo") 23 .append("indexShapes", true))))) 24 ); 25 collection.createSearchIndex(indexName, searchIdx); 26 System.out.println("New index name: " + indexName); 27 } catch (Exception e) { 28 System.err.println("Error creating Atlas Search index: " + e.getMessage()); 29 } 30 } 31 }
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Initialize your Node.js project.
Create a new directory and initialize the project mkdir atlas-search-project && cd atlas-search-project npm init -y Add the MongoDB Node.js Driver to your project npm install mongodb
For detailed installation instructions, see the MongoDB Node Driver documentation.
Define the index.
Create a create-index.js file in your project directory, and copy and paste the following code into the file.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the connection string with your MongoDB deployment's connection string 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("<database>"); 11 const collection = database.collection("<collection>"); 12 13 // Create the MongoDB Search index definition for the geo field 14 const index = { 15 name: "default", 16 definition: { 17 "mappings": { 18 "dynamic": true|false, 19 "fields": { 20 "<field-name>": { 21 "type": "geo", 22 "indexShapes": true|false 23 } 24 } 25 } 26 } 27 } 28 29 // Create the index 30 const result = await collection.createSearchIndex(index); 31 console.log("New index name: " + result); 32 } finally { 33 await client.close(); 34 } 35 } 36 37 run().catch(console.dir);
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 const { MongoClient } = require("mongodb"); 2 3 // Replace the connection string with your MongoDB deployment's connection string 4 const uri = "<connection-string>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 const database = client.db("sample_airbnb"); 11 const collection = database.collection("listingsAndReviews"); 12 13 // Create the MongoDB Search index definition for the geo field 14 const index = { 15 name: "default", 16 definition: { 17 "mappings": { 18 "dynamic": false, 19 "fields": { 20 "address": { 21 "type": "document", 22 "fields": { 23 "location": { 24 "type": "geo", 25 "indexShapes": true 26 } 27 } 28 } 29 } 30 } 31 } 32 } 33 34 // Create the index 35 const result = await collection.createSearchIndex(index); 36 console.log("New index name: " + result); 37 } finally { 38 await client.close(); 39 } 40 } 41 42 run().catch(console.dir);
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages:
You can use the MongoDB Search geo type to index geographic points and shape coordinates. For this type, the indexed field must be a GeoJSON object. You can use the geoShape and geoWithin operators to query indexed fields of type geo.
geo type is not included in the dynamic mapping by default. To index fields as geo type, you can use static mappings or configure a typeSet to include geo in dynamic mapping.
Define the Index for the geo Type
Set up the Python project.
Create a new directory for the project mkdir atlas-search-project && cd atlas-search-project Install PyMongo pip install pymongo
For detailed installation instructions, see the MongoDB PyMongo Driver documentation.
Define the index.
Create a create_index.py file in your project directory, and copy and paste the following code into the file.
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # Connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 database = client["<database>"] 9 collection = database["<collection>"] 10 11 # Create the MongoDB Search index definition for the geo field 12 search_index_model = SearchIndexModel( 13 definition={ 14 "mappings": { 15 "dynamic": true|false, 16 "fields": { 17 "<field-name>":{ 18 "type": "geo", 19 "indexShapes": true|false 20 } 21 } 22 }, 23 }, 24 name="default", 25 ) 26 27 # Create the index 28 result = collection.create_search_index(model=search_index_model) 29 print(f"New index name: {result}")
Replace <connection-string> with the connection string for your Atlas cluster or local Atlas deployment.
To learn more about finding your connection string, see Connect to a Cluster via Client Libraries.
Note
For a local or self-managed deployment, your connection string should use the following format:
mongodb://localhost:<port-number>/?directConnection=true
To learn more, see Connection Strings.
Configure geo Field Properties
The MongoDB Search geo type takes the following parameters:
Option | Type | Necessity | Description | Default |
|---|---|---|---|---|
| string | Required | Human-readable label that identifies this field type. UI value must be | |
| boolean | Optional | Flag that indicates whether to index shapes. By default, MongoDB Search:
Value can be:
|
|
Try an Example for the geo Type
The following index definition examples use collections in the sample data. After you load the sample data, you can use these examples to index fields as the geo type.
To learn how to set up and run the following example code, see Define the Index for the token Type.
The following index definition for the sample_airbnb.listingsAndReviews collection indexes the address.location field as the geo type. This index allows you to query against that field by using the MongoDB Search geoShape and geoWithin operators.
1 from pymongo import MongoClient 2 from pymongo.operations import SearchIndexModel 3 4 # Connect to your Atlas deployment 5 uri = "<connection-string>" 6 client = MongoClient(uri) 7 8 database = client["sample_airbnb"] 9 collection = database["listingsAndReviews"] 10 11 # Create the MongoDB Search index definition for the geo field 12 search_index_model = SearchIndexModel( 13 definition={ 14 "mappings": { 15 "dynamic": false, 16 "fields": { 17 "address": { 18 "type": "document", 19 "fields": { 20 "location": { 21 "type": "geo", 22 "indexShapes": true 23 } 24 } 25 } 26 } 27 }, 28 }, 29 name="default", 30 ) 31 32 # Create the index 33 result = collection.create_search_index(model=search_index_model) 34 print(f"New index name: {result}")
Learn More
To learn more about the operators you can use to query the geo type, see the following operator reference pages: