For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

How to Index GeoJSON Objects

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.

1

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.

2

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 step

  • Replace {groupId} with the project ID of the project where you want to create the MongoDB Search index

  • Replace {clusterName} with the name of the cluster where you want to create the MongoDB Search index

1curl --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 }'

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1curl --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 }'

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.

1
search-index.json
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}
2

In your terminal, connect to your cluster from the Atlas CLI. To learn more, see Connect from the Atlas CLI.

3

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>

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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}

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.

1

Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.

2

On the Database screen, click the name of the database, then click the name of the collection.

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Atlas Search Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your MongoDB Search index is named default by 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 different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. 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}
  5. Click Create Search Index.

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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}

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.

1

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.

2
use <database>
switched to db <database>
3
db.<collection>.createSearchIndex(
"default",
{
"mappings": {
"dynamic": false,
"fields": {
"<field-name>": {
"type": "geo",
"indexShapes": true|false
}
}
}
}
)
default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1db.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)

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.

Choose your preferred configuration method in the Atlas UI and then select the database and collection.

  1. Click Refine Your Index to configure your index.

  2. In the Field Mappings section, click Add Field Mapping to open the Add Field Mapping window.

  3. Click Customized Configuration.

  4. 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.

  5. Click the Data Type dropdown and select Geo.

  6. Configure the field properties for the geo type. To learn more, see Field Properties.

  7. Click Add.

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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. In the Add Field Mapping window, select address.location from the Field Name dropdown.

  2. Click the Data Type dropdown and select Geo.

  3. Modify the Geo Properties to set the value for Index Shapes to true.

  4. Click Add.

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.

1

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
2mkdir atlas-search-project && cd atlas-search-project

Add the C driver to your project by following the instructions in the MongoDB C Driver documentation.

2

Create a create_index.c file in your project directory, and copy and paste the following code into the file.

create_index.c
1#include <mongoc/mongoc.h>
2#include <stdio.h>
3
4int 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.

3

To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:

CMakeLists.txt
1cmake_minimum_required(VERSION 3.11)
2project(atlas-search-index LANGUAGES C)
3add_executable (index.out create_index.c)
4find_package(mongoc <version> REQUIRED)
5target_link_libraries(index.out mongoc::mongoc)

The preceding code performs the following actions:

  • Configures a C project.

  • Creates a index.out executable for your application.

  • Finds and requires the C driver. Replace the <version> placeholder with your C driver version, such as 2.0.0.

  • Links the program to the libmongoc library.

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.

4

In your terminal, run the following commands to build and run this application:

cmake -S. -Bcmake-build
cmake --build cmake-build --target index.out
./cmake-build/index.out
Index created!

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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#include <mongoc/mongoc.h>
2#include <stdio.h>
3
4int 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}

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.

1

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.

2

Paste the following code into the Program.cs file.

Program.cs
1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// Replace the connection string with your MongoDB deployment's connection string
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("<database>");
10var collection = db.GetCollection<BsonDocument>("<collection>");
11
12// Create the MongoDB Search index definition for the geo field
13var 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
33var result = collection.SearchIndexes.CreateOne(index);
34Console.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.

3
dotnet run Program.cs
New index name: default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// Replace the connection string with your MongoDB deployment's connection string
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("sample_airbnb");
10var collection = db.GetCollection<BsonDocument>("listingsAndReviews");
11
12// Create the MongoDB Search index definition for the geo field
13var 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
42var result = collection.SearchIndexes.CreateOne(index);
43Console.WriteLine($"New index name: {result}");

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.

1

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.

2

Create a CreateIndex.cpp file in your project directory, and copy and paste the following code into the file.

CreateIndex.cpp
1#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12int 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.

3
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

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12int 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}

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.

1

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.

2

Create a create_index.go file in your project directory, and copy and paste the following code into the file.

create_index.go
1package main
2
3import (
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
13func 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.

3
go run create_index.go
New index name: default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1package main
2
3import (
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
13func 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}

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.

1

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>

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:

pom.xml
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.11.1</version>
</dependency>
</dependencies>

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.

2

In your project's base package directory, create a CreateIndex.java file and copy and paste the following code into this file.

CreateIndex.java
1import com.mongodb.client.*;
2import org.bson.Document;
3
4public 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.

3

Compile and run your application in your IDE or your shell.

javac CreateIndex.java
java CreateIndex
New index name: default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1import com.mongodb.client.*;
2import org.bson.Document;
3
4public 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}

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.

1
# 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.

2

Create a create-index.js file in your project directory, and copy and paste the following code into the file.

create-index.js
1const { MongoClient } = require("mongodb");
2
3// Replace the connection string with your MongoDB deployment's connection string
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async 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
37run().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.

3
node create-index.js
New index name: default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1const { MongoClient } = require("mongodb");
2
3// Replace the connection string with your MongoDB deployment's connection string
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async 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
42run().catch(console.dir);

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.

1
# 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.

2

Create a create_index.py file in your project directory, and copy and paste the following code into the file.

create_index.py
1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# Connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8database = client["<database>"]
9collection = database["<collection>"]
10
11# Create the MongoDB Search index definition for the geo field
12search_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
28result = collection.create_search_index(model=search_index_model)
29print(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.

3
python create_index.py
New index name: default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# Connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8database = client["sample_airbnb"]
9collection = database["listingsAndReviews"]
10
11# Create the MongoDB Search index definition for the geo field
12search_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
33result = collection.create_search_index(model=search_index_model)
34print(f"New index name: {result}")

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.

1
search-index.json
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}
2

In your terminal, connect to your local deployment from the Atlas CLI. To learn more, see Connect from the Atlas CLI.

3

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>

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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}

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.

1

Open Compass and connect to your cluster. For detailed instructions, see Connect to a Cluster via Compass.

2

On the Database screen, click the name of the database, then click the name of the collection.

3
  1. Click the Indexes tab, then select Search Indexes.

  2. Click Create Atlas Search Index to open the index creation dialog box.

  3. Specify a name for the index.

    Your MongoDB Search index is named default by 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 different index option in its operators. If you are creating multiple indexes, we recommend that you maintain a consistent, descriptive naming convention across your indexes.

  4. 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}
  5. Click Create Search Index.

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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}

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.

1

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.

2
use <database>
switched to db <database>
3
db.<collection>.createSearchIndex(
"default",
{
"mappings": {
"dynamic": false,
"fields": {
"<field-name>": {
"type": "geo",
"indexShapes": true|false
}
}
}
}
)
default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1db.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)

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.

1

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
2mkdir atlas-search-project && cd atlas-search-project

Add the C driver to your project by following the instructions in the MongoDB C Driver documentation.

2

Create a create_index.c file in your project directory, and copy and paste the following code into the file.

create_index.c
1#include <mongoc/mongoc.h>
2#include <stdio.h>
3
4int 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.

3

To configure your application, create a CMakeLists.txt file in your project directory. Then, add the following code to the file:

CMakeLists.txt
1cmake_minimum_required(VERSION 3.11)
2project(atlas-search-index LANGUAGES C)
3add_executable (index.out create_index.c)
4find_package(mongoc <version> REQUIRED)
5target_link_libraries(index.out mongoc::mongoc)

The preceding code performs the following actions:

  • Configures a C project.

  • Creates a index.out executable for your application.

  • Finds and requires the C driver. Replace the <version> placeholder with your C driver version, such as 2.0.0.

  • Links the program to the libmongoc library.

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.

4

In your terminal, run the following commands to build and run this application:

cmake -S. -Bcmake-build
cmake --build cmake-build --target index.out
./cmake-build/index.out
Index created!

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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#include <mongoc/mongoc.h>
2#include <stdio.h>
3
4int 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}

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.

1

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.

2

Paste the following code into the Program.cs file.

Program.cs
1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// Replace the connection string with your MongoDB deployment's connection string
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("<database>");
10var collection = db.GetCollection<BsonDocument>("<collection>");
11
12// Create the MongoDB Search index definition for the geo field
13var 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
33var result = collection.SearchIndexes.CreateOne(index);
34Console.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.

3
dotnet run Program.cs
New index name: default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1using MongoDB.Bson;
2using MongoDB.Driver;
3
4// Replace the connection string with your MongoDB deployment's connection string
5var uri = "<connection-string>";
6
7var client = new MongoClient(uri);
8
9var db = client.GetDatabase("sample_airbnb");
10var collection = db.GetCollection<BsonDocument>("listingsAndReviews");
11
12// Create the MongoDB Search index definition for the geo field
13var 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
42var result = collection.SearchIndexes.CreateOne(index);
43Console.WriteLine($"New index name: {result}");

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.

1

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.

2

Create a CreateIndex.cpp file in your project directory, and copy and paste the following code into the file.

CreateIndex.cpp
1#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12int 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.

3
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

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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#include <iostream>
2
3#include <bsoncxx/builder/basic/document.hpp>
4#include <bsoncxx/json.hpp>
5#include <mongocxx/client.hpp>
6#include <mongocxx/instance.hpp>
7#include <mongocxx/uri.hpp>
8
9using bsoncxx::builder::basic::kvp;
10using bsoncxx::builder::basic::make_document;
11
12int 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}

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.

1

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.

2

Create a create_index.go file in your project directory, and copy and paste the following code into the file.

create_index.go
1package main
2
3import (
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
13func 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.

3
go run create_index.go
New index name: default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1package main
2
3import (
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
13func 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}

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.

1

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>

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:

pom.xml
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.11.1</version>
</dependency>
</dependencies>

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.

2

In your project's base package directory, create a CreateIndex.java file and copy and paste the following code into this file.

CreateIndex.java
1import com.mongodb.client.*;
2import org.bson.Document;
3
4public 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.

3

Compile and run your application in your IDE or your shell.

javac CreateIndex.java
java CreateIndex
New index name: default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1import com.mongodb.client.*;
2import org.bson.Document;
3
4public 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}

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.

1
# 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.

2

Create a create-index.js file in your project directory, and copy and paste the following code into the file.

create-index.js
1const { MongoClient } = require("mongodb");
2
3// Replace the connection string with your MongoDB deployment's connection string
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async 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
37run().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.

3
node create-index.js
New index name: default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1const { MongoClient } = require("mongodb");
2
3// Replace the connection string with your MongoDB deployment's connection string
4const uri = "<connection-string>";
5
6const client = new MongoClient(uri);
7
8async 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
42run().catch(console.dir);

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.

1
# 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.

2

Create a create_index.py file in your project directory, and copy and paste the following code into the file.

create_index.py
1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# Connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8database = client["<database>"]
9collection = database["<collection>"]
10
11# Create the MongoDB Search index definition for the geo field
12search_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
28result = collection.create_search_index(model=search_index_model)
29print(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.

3
python create_index.py
New index name: default

The MongoDB Search geo type takes the following parameters:

Option
Type
Necessity
Description
Default

type

string

Required

Human-readable label that identifies this field type. UI value must be Geo and JSON value must be geo.

indexShapes

boolean

Optional

Flag that indicates whether to index shapes. By default, MongoDB Search:

  • Indexes points, even when nested.

  • Doesn't index shape geometries such as lines and polygons.

Value can be:

  • true to index shapes and points

  • false to index only points

false

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.

1from pymongo import MongoClient
2from pymongo.operations import SearchIndexModel
3
4# Connect to your Atlas deployment
5uri = "<connection-string>"
6client = MongoClient(uri)
7
8database = client["sample_airbnb"]
9collection = database["listingsAndReviews"]
10
11# Create the MongoDB Search index definition for the geo field
12search_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
33result = collection.create_search_index(model=search_index_model)
34print(f"New index name: {result}")

To learn more about the operators you can use to query the geo type, see the following operator reference pages:

Rate this page