- Indexes >
geoHaystack
Indexes >- Create a Haystack Index
Create a Haystack Index¶
Deprecation
MongoDB 4.4 deprecates the geoHaystack index and the
geoSearch
command. Use a 2d index
with $geoNear
or $geoWithin
instead.
A haystack index must reference two fields: the location field and a second field. The second field is used for exact matches. Haystack indexes return documents based on location and an exact match on a single additional criterion. These indexes are not necessarily suited to returning the closest documents to a particular location.
To build a haystack index, use the following syntax:
To build a haystack index, you must specify the bucketSize
option
when creating the index. A bucketSize
of 5
creates an index
that groups location values that are within 5 units of the specified
longitude and latitude. The bucketSize
also determines the
granularity of the index. You can tune the parameter to the
distribution of your data so that in general you search only very small
regions. The areas defined by buckets can overlap. A document can exist
in multiple buckets.
Example
If you have a collection with documents that contain fields similar to the following:
The following operations create a haystack index with buckets that store keys within 1 unit of longitude or latitude.
This index stores the document with an _id
field that has the
value 200
in two different buckets:
- In a bucket that includes the document where the
_id
field has a value of100
- In a bucket that includes the document where the
_id
field has a value of300
To query using a haystack index you use the geoSearch
command. See Query a Haystack Index.
By default, queries that use a haystack index return 50 documents.