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