2d Indexes

Use a 2d index for data stored as points on a two-dimensionalplane. The 2d index is intended for legacy coordinate pairs used in MongoDB 2.2 and earlier.

Use a 2d index if:

For more information on geospatial queries, seeGeospatial Queries.

Considerations

Starting in MongoDB 4.0, you can specify a key option to the$geoNear pipeline stage to indicate the indexed field pathto use. This allows the $geoNear stage to be used on acollection that has multiple 2d index and/or multiple2dsphere index:

  • If your collection has multiple 2d index and/or multiple2dsphere index, you must use the key option to specify theindexed field path to use.
  • If you do not specify the key, you cannot have multiple2d index and/or multiple 2dsphere index since withoutthe key, index selection among multiple 2d indexes or2dsphere indexes is ambiguous.

Note

If you do not specify the key, and you have at most only one2d index index and/or only one 2d index index,MongoDB looks first for a 2d index to use. If a 2d indexdoes not exists, then MongoDB looks for a 2dsphere index to use.

Do not use a 2d index if your location data includes GeoJSONobjects. To index on both legacy coordinate pairsandGeoJSON objects,use a 2dsphere index.

You cannot use a 2d index as a shard key when sharding acollection. However, you can create a geospatial indexon a sharded collection by using a different field as the shard key.

Behavior

The 2d index supports calculations on a flat, Euclidean plane. The 2d index also supports distance-only_calculations on a sphere (i.e. $nearSphere), but for_geometric calculations on a sphere (e.g. $geoWithin), storedata as GeoJSON objects and use a2dsphere index.

A 2d index can reference two fields. The first must be the locationfield. A 2d compound index constructs queries that select first onthe location field, and then filters those results by the additionalcriteria. A compound 2d index can cover queries.

sparse Property

2d indexes are always sparse andignore the sparse option. If adocument lacks a 2d index field (or the field is null or anempty array), MongoDB does not add an entry for the document to the2d index. For inserts, MongoDB inserts the document but does notadd to the 2d index.

For a compound index that includes a 2d index key along with keysof other types, only the 2d index field determines whether theindex references a document.

Collation Option

2d indexes only support simple binary comparison and do not supportthe collation option.

To create a 2d index on a collection that has a non-simplecollation, you must explicitly specify {collation: {locale: "simple"}} when creating the index.