From ea1a9516dbad693701f8fd2777b87048db701570 Mon Sep 17 00:00:00 2001 From: Bob Grabar Date: Wed, 13 Mar 2013 13:44:07 -0400 Subject: [PATCH] DOCS-641 Geospatial --- bin/builder_data.py | 1 + source/administration/indexes.txt | 4 - source/applications/2d.txt | 268 ++++++ source/applications/2dsphere.txt | 255 +++++ source/applications/geohaystack.txt | 122 +++ source/applications/geospatial-indexes.txt | 457 ++------- source/core/geospatial-indexes.txt | 421 +-------- .../note-geospatial-index-must-exist.rst | 16 +- source/includes/table-geospatial-queries.yaml | 174 ++++ source/indexes.txt | 24 +- source/reference/command/geoNear.txt | 45 +- source/reference/geospatial-queries.txt | 13 + source/reference/glossary.txt | 43 +- source/reference/operator/box.txt | 35 +- source/reference/operator/center.txt | 37 +- source/reference/operator/centerSphere.txt | 50 +- source/reference/operator/geoIntersects.txt | 55 ++ source/reference/operator/geoWithin.txt | 97 ++ source/reference/operator/geometry.txt | 19 + source/reference/operator/maxDistance.txt | 31 +- source/reference/operator/near.txt | 77 +- source/reference/operator/nearSphere.txt | 38 +- source/reference/operator/polygon.txt | 36 +- source/reference/operator/uniqueDocs.txt | 38 +- source/reference/operator/within.txt | 59 -- source/reference/operators.txt | 15 +- source/release-notes.txt | 1 + source/release-notes/2.4-javascript.txt | 438 --------- source/release-notes/2.4.txt | 870 +++++++++++++----- ...al-geometry-with-2d-geospatial-indexes.txt | 154 ++++ 30 files changed, 2227 insertions(+), 1666 deletions(-) create mode 100644 source/applications/2d.txt create mode 100644 source/applications/2dsphere.txt create mode 100644 source/applications/geohaystack.txt create mode 100644 source/includes/table-geospatial-queries.yaml create mode 100644 source/reference/geospatial-queries.txt create mode 100644 source/reference/operator/geoIntersects.txt create mode 100644 source/reference/operator/geoWithin.txt create mode 100644 source/reference/operator/geometry.txt delete mode 100644 source/reference/operator/within.txt delete mode 100644 source/release-notes/2.4-javascript.txt create mode 100644 source/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes.txt diff --git a/bin/builder_data.py b/bin/builder_data.py index ba442438fd0..55f82d3e3d8 100644 --- a/bin/builder_data.py +++ b/bin/builder_data.py @@ -53,6 +53,7 @@ ('$(public-branch-output)/reference/mongo-shell-reference', 'mongo-shell', 'redirect'), ('$(public-branch-output)/reference/method/getShardDistribution', 'db.collection.getShardDistribution', 'redirect'), ('$(public-branch-output)/reference/method/getDB', 'Mongo.getDB', 'redirect'), + ('$(public-branch-output)/reference/operator/within', 'geoWithin', 'redirect'), ('$(public-branch-output)/reference/method/getShardVersion', 'db.collection.getShardVersion', 'redirect'), ('$(public-branch-output)/reference/command/whatsMyUri', 'whatsmyuri', 'redirect'), ('$(public-branch-output)/reference/command/writeBackListen', 'writebacklisten', 'redirect'), diff --git a/source/administration/indexes.txt b/source/administration/indexes.txt index f46a9718aef..d2ac00c2a40 100644 --- a/source/administration/indexes.txt +++ b/source/administration/indexes.txt @@ -99,10 +99,6 @@ Special Creation Options TTL collections use a special ``expire`` index option. See :doc:`/tutorial/expire-data` for more information. -.. note:: - - To create geospatial indexes, see :ref:`geospatial-indexes-create`. - .. index:: index; sparse .. _index-sparse-index: diff --git a/source/applications/2d.txt b/source/applications/2d.txt new file mode 100644 index 00000000000..49b7a17b1b9 --- /dev/null +++ b/source/applications/2d.txt @@ -0,0 +1,268 @@ +============== +``2d`` Indexes +============== + +.. default-domain:: mongodb + +Use a ``2d`` index for data stored as points on a two-dimensional plane. The +``2d`` index is intended for legacy coordinate pairs used in MongoDB 2.2 +and earlier. + +Use a ``2d`` index if: + +- your database has legacy location data from MongoDB 2.2 or earlier, *and* + +- you do not intend to store any location data as :term:`GeoJSON` objects. + +Do not use a ``2d`` index if your location data includes GeoJSON objects. To +index on both legacy coordinate pairs *and* GeoJSON objects, use a +:doc:`2dsphere index `. + +The ``2d`` index supports calculations on a flat, Euclidean plane. The +``2d`` index also supports *distance-only* calculations on a sphere, but +for *geometric* calculations on a sphere, store data as GeoJSON objects +and use the ``2dsphere`` index type. + +A ``2d`` index can reference two fields. The first must be the location +field. A ``2d`` compound index constructs queries that select first on +the location field and second on the additional field. If the location +criteria selects a large number of documents, the additional criteria +only filters the result set. The additional criteria *does not* result +in a more targeted query. + +MongoDB allows one ``2d`` index per collection. + +.. important:: You cannot use a ``2d`` index as a shard key when + sharding a collection. However, you can create and maintain a + geospatial index on a sharded collection by using a different field + as the shard key. + +.. _geospatial-indexes-store-grid-coordinates: + +Store Points on a 2D Plane +-------------------------- + +To store location data as legacy coordinate pairs, use either an array +(preferred): + +.. code-block:: javascript + + loc : [ , ] + +Or an embedded document: + +.. code-block:: javascript + + loc : { long : , lat : } + +Arrays are preferred as certain languages do not guarantee associative +map ordering. + +Whether as an array or document, if you use longitude and latitude, +store coordinates in this order: **longitude, latitude**. + +.. _geospatial-create-2d-index: + +Create a ``2d`` Index +--------------------- + +To build a geospatial ``2d`` index, use the :method:`ensureIndex() +` method and specify ``2d``. Use the +following syntax: + +.. code-block:: javascript + + db..ensureIndex( { : "2d" , : } , + { } ) + +The ``2d`` index uses the following optional index-specification +options: + +.. code-block:: javascript + + { min : , max : , + bits : } + +.. _geospatial-indexes-range: + +Define Location Range for a ``2d`` Index +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +By default, a ``2d`` index assumes longitude and latitude and has boundaries +of -180 inclusive and 180 non-inclusive (i.e. ``[ -180 , 180 ]``). If +documents contain coordinate data outside of the specified range, +MongoDB returns an error. + +.. important:: The default boundaries allow applications to insert + documents with invalid latitudes greater than 90 or less than -90. + The behavior of geospatial queries with such invalid points is not + defined. + +On ``2d`` indexes you can change the location range. + +You can build a ``2d`` geospatial index with a location range other than +the default. Use the ``min`` and ``max`` options when creating the +index. Use the following syntax: + +.. code-block:: javascript + + db.collection.ensureIndex( { : "2d" } , + { min : , max : } ) + +.. _geospatial-indexes-precision: + +Define Location Precision for a ``2d`` Index +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +By default, a ``2d`` index on legacy coordinate pairs uses 26 bits of +precision, which is roughly equivalent to 2 feet or 60 centimeters of +precision using the default range of -180 to 180. Precision is measured +by the size in bits of the :term:`geohash` values used to store location +data. You can configure geospatial indexes with up to 32 bits of +precision. + +Index precision does not affect query accuracy. The actual grid coordinates +are always used in the final query processing. Advantages to lower +precision are a lower processing overhead for insert operations and use +of less space. An advantage to higher precision is that queries scan +smaller portions of the index to return results. + +To configure a location precision other than the default, use the +``bits`` option when creating the index. Use following syntax: + +.. code-block:: javascript + + db..ensureIndex( { : ""} , + { bits : } ) + +For information on the internals of geohash values, see +:ref:`geospatial-indexes-geohash`. + +Query a ``2d`` Index +-------------------- + +The following sections describe queries supported by the ``2d`` index. +For an overview of recommended geospatial queries, see +:doc:`/reference/geospatial-queries`. + +Points within a Shape Defined on a Flat Surface +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To select all legacy coordinate pairs found within a given shape on a flat +surface, use the :operator:`$geoWithin` operator along with a shape +operator. Use the following syntax: + +.. code-block:: javascript + + db..find( { : + { $geoWithin : + { $box|$polygon|$center : + } } } ) + +The following queries for documents within a rectangle defined by ``[ 0 +, 0 ]`` at the bottom left corner and by ``[ 100 , 100 ]`` at the top +right corner. + +.. code-block:: javascript + + db.places.find( { loc : { $geoWithin : { $box : + [ [ 0 , 0 ] , + [ 100 , 100 ] ] } } } ) + +The following queries for documents that are within the circle centered +on ``[ -74 , 40.74 ]`` and with a radius of ``10``: + +.. code-block:: javascript + + db.places.find( { loc: { $geoWithin : + { $center : [ [-74, 40.74], 10 ] } + } } ) + +For syntax and examples for each shape, see the following: + + - :operator:`$box` + + - :operator:`$polygon` + + - :operator:`$center` (defines a circle) + +Points within a Circle Defined on a Sphere +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +MongoDB supports rudimentary spherical queries on flat ``2d`` indexes for +legacy reasons. In general, spherical calculations should use a ``2dsphere`` +index, as described in :doc:`/applications/2dsphere`. + +To query for legacy coordinate pairs in a "spherical cap" on a sphere, +use :operator:`$geoWithin` with the :operator:`$centerSphere` operator. +Specify an array that contains: + +- The grid coordinates of the circle's center point + +- The circle's radius measured in radians. To calculate radians, see + :doc:`/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes`. + +Use the following syntax: + +.. code-block:: javascript + + db..find( { : + { $geoWithin : + { $centerSphere : [ [ , ] , ] } + } } ) + +The following example query returns all documents within a 10-mile +radius of longitude ``88 W`` and latitude ``30 N``. The example converts +distance to radians by dividing distance by the approximate radius of +the earth, 3959 miles: + +.. code-block:: javascript + + db..find( { loc : { $geoWithin : + { $centerSphere : + [ [ 88 , 30 ] , 10 / 3959 ] + } } } ) + +Proximity to a Point on a Flat Surface +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Proximity queries return the 100 legacy coordinate pairs closest to the +defined point and sort the results by distance. Use either the +:operator:`$near` operator or :dbcommand:`geoNear` command. Both require +a ``2d`` index. + +The :operator:`$near` operator uses the following syntax: + +.. code-block:: javascript + + db..find( { : + { $near : [ , ] + } } ) + +For examples, see :operator:`$near`. + +The :dbcommand:`geoNear` command uses the following syntax: + +.. code-block:: javascript + + db.runCommand( { geoNear: , near: [ , ] } ) + +The :dbcommand:`geoNear` command offers more options and returns more +information than does the :operator:`$near` operator. To run the +command, see :dbcommand:`geoNear`. + +.. index:: geospatial queries +.. index:: geospatial queries; exact +.. _geospatial-indexes-exact-match: + +Exact Matches on a Flat Surface +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You can use the :method:`db.collection.find()` method to query for an +exact match on a location. These queries use the following syntax: + +.. code-block:: javascript + + db..find( { : [ , ] } ) + +This query will return any documents with the value of ``[ , ]``. diff --git a/source/applications/2dsphere.txt b/source/applications/2dsphere.txt new file mode 100644 index 00000000000..4cb2498bc8a --- /dev/null +++ b/source/applications/2dsphere.txt @@ -0,0 +1,255 @@ +==================== +``2dsphere`` Indexes +==================== + +.. default-domain:: mongodb + +.. versionadded:: 2.4 + +A ``2dsphere`` index supports queries that calculate geometries on a +sphere. The index supports data stored as both :term:`GeoJSON` objects +and as legacy coordinate pairs. The ``2dsphere`` index supports legacy +coordinate pairs by converting the data to the GeoJSON Point type. + +The ``2dsphere`` index supports all MongoDB geospatial queries: queries +for inclusion, intersection and proximity. + +MongoDB allows one ``2dsphere`` index per collection. + +A :ref:`compound ` ``2dsphere`` index can reference +multiple location and non-location fields within a collection’s +documents. You can arrange the fields in any order. + +The default datum for a sphere in MongoDB 2.4 is WGS84 - SRID 4326. +Coordinate-axis order is "longitude, latitude." + +.. important:: You cannot use a ``2d`` index as a shard key when + sharding a collection. However, you can create and maintain a + geospatial index on a sharded collection by using a different field + as the shard key. + +.. _geospatial-indexes-store-geojson: + +Store GeoJSON Objects +--------------------- + +.. versionadded:: 2.4 + +MongoDB supports the following GeoJSON objects: + + - Point + + - LineString + + - Polygon + +In order to index GeoJSON data, you must store the data in a location +field that you name. The location field contains a subdocument with a +``type`` field specifying the GeoJSON object type and a ``coordinates`` +field specifying the object's coordinates. Always store coordinates in +this order: **longitude, latitude.** + +Use the following syntax: + +.. code-block:: javascript + + { : { type : "" , + coordinates : + } } + +The following example stores a GeoJSON ``Point``: + +.. code-block:: javascript + + { loc : { type : "Point" , + coordinates : [ 40, 5 ] + } } + +The following example stores a GeoJSON ``LineString``: + +.. code-block:: javascript + + { loc : { type : "LineString" , + coordinates : [ [ 40 , 5 ] , [ 41 , 6 ] ] + } } + +The following example stores a GeoJSON ``Polygon`` with an exterior ring +and no interior rings (or holes): + +.. code-block:: javascript + + { loc : + { type : "Polygon" , + coordinates : [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ] ] + } } + +.. _geospatial-indexes-create-2dsphere: + +Create a ``2dsphere`` Index +--------------------------- + +To create a geospatial index for GeoJSON-formatted data, use the +:method:`~db.collection.ensureIndex()` method and set the +value of the location field for your collection to ``2dsphere``. A +``2dsphere`` index can be a :ref:`compound index ` +and does not require the location field to be the first field indexed. + +To create the index use the following syntax: + +.. code-block:: javascript + + db.collection.ensureIndex( { : "2dsphere" } ) + +The following are four example commands for creating a ``2dsphere`` index: + +.. code-block:: javascript + + db.collection.ensureIndex( { loc : "2dsphere" } ) + db.collection.ensureIndex( { loc : "2dsphere", type : 1 } ) + db.collection.ensureIndex( { type : 1, loc : "2dsphere" } ) + db.collection.ensureIndex( { loc : "2dsphere", type : 1, rating : -1 } ) + +The first example creates a simple geospatial index on the location +field ``loc``. The second example creates a compound index where the +second field contains non-location data. The third example creates an +index where the location field is not the primary field: the location +field does not have to be the first field in a ``2dsphere`` index. The +fourth example creates a compound index with three fields: you can +include as many fields as you like in a ``2dsphere`` index. + +Query a ``2dsphere`` Index +-------------------------- + +The following sections describe queries supported by the ``2dsphere`` index. +For an overview of recommended geospatial queries, see +:doc:`/reference/geospatial-queries`. + +GeoJSON Objects Bounded by a Polygon +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To select all points and shapes found within a GeoJSON polygon, your +data must be stored in GeoJSON format. Use the following syntax: + +.. code-block:: javascript + + db..find( { : + { $geoWithin : + { $geometry : + { type : "Polygon" , + coordinates : [ ] + } } } } ) + +The following example selects all points and shapes that +exist entirely within a GeoJSON polygon: + +.. code-block:: javascript + + db.places.find( { loc : + { $geoWithin : + { $geometry : + { type : "Polygon" , + coordinates : [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ] ] + } } } } ) + +Intersections of GeoJSON Objects +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 2.4 + +The :operator:`$geoIntersects` operator queries for location data that +intersects a GeoJSON object. Use the following syntax: + +.. code-block:: javascript + + db..find( { : + { $geoIntersects : + { $geometry : + { type : "" , + coordinates : [ ] + } } } } ) + +The following example uses :operator:`$geoIntersects` to select all +indexed points and shapes that intersect with the polygon defined by the +``coordinates`` array. + +.. code-block:: javascript + + db.places.find( { loc : + { $geoIntersects : + { $geometry : + { type : "Polygon" , + coordinates: [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ] ] + } } } } ) + +The query returns true if the intersection between shapes is non-empty. +This includes documents that have a shared edge. + +Proximity to a GeoJSON Point +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Proximity queries return the 100 points closest to the defined point and +sorts the results by distance. A proximity query on GeoJSON data +requires a ``2dsphere`` index. + +To query for proximity to a GeoJSON point, use either the +:operator:`$near` operator or :dbcommand:`geoNear` command. Distance +is in meters. + +The :operator:`$near` uses the following syntax: + +.. code-block:: javascript + + db..find( { : + { $near : + { $geometry : + { type : "Point" , + coordinates : [ , ] } , + $maxDistance : + } } } ) + +For examples, see :operator:`$near`. + +The :dbcommand:`geoNear` command uses the following syntax: + +.. code-block:: javascript + + db.runCommand( { geoNear: , near: [ , ] } ) + +The :dbcommand:`geoNear` command offers more options and returns more +information than does the :operator:`$near` operator. To run the +command, see :dbcommand:`geoNear`. + +Points within a Circle Defined on a Sphere +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +To select all grid coordinates in a "spherical cap" on a sphere, use +:operator:`$geoWithin` with the :operator:`$centerSphere` operator. +Specify an array that contains: + +- The grid coordinates of the circle's center point + +- The circle's radius measured in radians. To calculate radians, see + :doc:`/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes`. + +Use the following syntax: + +.. code-block:: javascript + + db..find( { : + { $geoWithin : + { $centerSphere : + [ [ , ] , ] } + } } ) + +The following example queries grid coordinates and returns all +documents within a 10 mile radius of longitude ``88 W`` and latitude +``30 N``. The example converts the distance, 10 miles, to radians by +dividing by the approximate radius of the earth, 3959 miles: + +.. code-block:: javascript + + db.places.find( { loc : + { $geoWithin : + { $centerSphere : + [ [ 88 , 30 ] , 10 / 3959 ] + } } } ) diff --git a/source/applications/geohaystack.txt b/source/applications/geohaystack.txt new file mode 100644 index 00000000000..a9a166a1b1a --- /dev/null +++ b/source/applications/geohaystack.txt @@ -0,0 +1,122 @@ +================ +Haystack Indexes +================ + +.. default-domain:: mongodb + +A haystack index is a special index that is optimized to return results +over small areas. Haystack indexes improve performance on queries that +use flat geometry. + +For queries that use spherical geometry, +a **2dsphere index is a better option** than a haystack index. 2dsphere +indexes allow field reordering; haystack indexes require the first field +to be the location field. Also, haystack indexes are only usable via +commands and so always return all results at once. + +Haystack indexes create "buckets" of documents from the same geographic +area in order to improve performance for queries limited to that area. +Each bucket in a haystack index contains all the documents within a +specified proximity to a given longitude and latitude. + +This document describes how to: + +- :ref:`geospatial-indexes-haystack-index` + +- :ref:`geospatial-indexes-haystack-queries` + +.. _geospatial-indexes-haystack-index: + +Create a Haystack Index +~~~~~~~~~~~~~~~~~~~~~~~ + +To build a haystack index, use 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. + +A haystack index can 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: + +.. code-block:: javascript + + db.coll.ensureIndex( { : "geoHaystack" , : 1 } , + { bucketSize : } ) + +.. example:: + + If you have a collection with documents that contain fields similar to + the following: + + .. code-block:: javascript + + { _id : 100, pos: { long : 126.9, lat : 35.2 } , type : "restaurant"} + { _id : 200, pos: { long : 127.5, lat : 36.1 } , type : "restaurant"} + { _id : 300, pos: { long : 128.0, lat : 36.7 } , type : "national park"} + + The following operations create a haystack index with buckets that + store keys within 1 unit of longitude or latitude. + + .. code-block:: javascript + + db.places.ensureIndex( { pos : "geoHaystack", type : 1 } , + { bucketSize : 1 } ) + + 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 of ``100`` + + - In a bucket that includes the document where the ``_id`` field has + a value of ``300`` + +To query using a haystack index you use the :dbcommand:`geoSearch` +command. See :ref:`geospatial-indexes-haystack-queries`. + +By default, queries that use a haystack index return 50 documents. + +.. _geospatial-indexes-haystack-queries: + +Query a Haystack Index +---------------------- + +A haystack index is a special ``2d`` geospatial index that is optimized +to return results over small areas. To create a haystack index see +:ref:`geospatial-indexes-haystack-index`. + +To query a haystack index, use the :dbcommand:`geoSearch` command. You +must specify both the coordinates and the additional +field to :dbcommand:`geoSearch`. For example, to return all documents +with the value ``restaurant`` in the ``type`` field near the example +point, the command would resemble: + +.. code-block:: javascript + + db.runCommand( { geoSearch : "places" , + search : { type: "restaurant" } , + near : [-74, 40.74] , + maxDistance : 10 } ) + +.. note:: + + Haystack indexes are not suited to queries for the complete list of + documents closest to a particular location. The closest documents + could be more distant compared to the bucket size. + +.. note:: + + :doc:`Spherical query operations + ` + are not currently supported by haystack indexes. + + The :method:`find() ` method and + :dbcommand:`geoNear` command cannot access the haystack index. diff --git a/source/applications/geospatial-indexes.txt b/source/applications/geospatial-indexes.txt index 39fd76242f6..b04a0870d04 100644 --- a/source/applications/geospatial-indexes.txt +++ b/source/applications/geospatial-indexes.txt @@ -1,418 +1,117 @@ -====================================== -Geospatial Queries with ``2d`` Indexes -====================================== +============================== +Geospatial Indexes and Queries +============================== .. default-domain:: mongodb -MongoDB provides support for querying location-based data using -special geospatial indexes. For an introduction to these ``2d`` -indexes, see :doc:`/core/geospatial-indexes`. +MongoDB offers a number of indexes and query mechanisms to handle +geospatial information. This section introduces MongoDB's geospatial +features. -MongoDB supports the following geospatial query types: +Surfaces +-------- -- Proximity queries, which select documents based on distance to a - given point. See :ref:`geospatial-indexes-proximity`. +Before storing your location data and writing queries, you must decide +the type of surface to use to perform calculations. The type you choose +affects how you store data, what type of index to build, and the syntax +of your queries. -- Bounded queries, which select documents that have coordinates within - a specified area. See :ref:`geospatial-indexes-bounded`. +MongoDB offers two surface types: -- Exact queries, which select documents with an exact coordinate pair, - which has limited applicability. See :ref:`geospatial-indexes-exact-match`. +- **Spherical** -.. index:: geospatial queries; proximity -.. _geospatial-indexes-near: -.. _geospatial-indexes-proximity: + To calculate geometries and distances on the earth, store your + location data on a spherical surface. Spherical surface calculations + requires slighly larger data sets but provide accurate data for + calculations on the earth. -Proximity Queries -~~~~~~~~~~~~~~~~~ + The default datum for a sphere in MongoDB 2.4 is WGS84 - SRID 4326. + Coordinate-axis order is "longitude, latitude." -Proximity queries select the documents closest to the point specified -in the query. To perform proximity queries you use either the -:method:`find() ` method with the -:operator:`$near` operator or you use the :dbcommand:`geoNear` -command. + If you perform calculations on a sphere, store your location data as + GeoJSON objects and use a ``2dsphere`` index. See + :doc:`/applications/2dsphere`. -The :method:`find() ` method with the -:operator:`$near` operator returns 100 documents by default and sorts -the results by distance. The :operator:`$near` operator uses the -following form: +- **Flat** -.. code-block:: javascript + To calculate distances on a Euclidean plane, store your location data + as points on a flat surface. Use the ``2d`` index. See + :doc:`/applications/2d`. - db.collection.find( { : { $near: [ x, y ] } } ) +Location Data +------------- -.. example:: +If you choose spherical surface calculations, you store location data as - The following query +- :term:`GeoJSON` objects (preferred). - .. code-block:: javascript + Queries on GeoJSON objects always calculate on a sphere. - db.places.find( { loc: { $near: [ -70, 40 ] } } ) + .. versionadded:: 2.4 The storage and querying of GeoJSON objects + is new in version 2.4. Prior to version 2.4, all geospatial data was + stored as coordinate pairs. - returns output similar to the following: +- :term:`Legacy coordinate pairs ` - .. code-block:: javascript + MongoDB supports spherical surface calculations on legacy coordinate + pairs by converting the data to the GeoJSON Point type. - { "_id" : ObjectId(" ... "), "loc" : [ -73, 39 ] } +If you choose flat surface calculations, you can store data only as +:term:`legacy coordinate pairs`. -The :dbcommand:`geoNear` command returns more information than does the -:operator:`$near` operator. The :dbcommand:`geoNear` command can only -return a single 16-megabyte result set. The -:dbcommand:`geoNear` command also offers additional operators, such as -operators to query for :ref:`maximum ` or -:ref:`spherical ` distance. For a list of -operators, see :dbcommand:`geoNear`. +Query Operations +---------------- -Without additional operators, the :dbcommand:`geoNear` command uses the -following form: +MongoDB's geospatial query operators let you query for: -.. code-block:: javascript +- **Inclusion**. MongoDB can query for locations contained entirely + within a specified geometry. Inclusion queries use the + :operator:`$geoWithin` operator. - db.runCommand( { geoNear: , near: [ x, y ] } ) +- **Intersection**. MongoDB can query for locations that intersect with + a specified geometry. These queries apply only to data on a spherical + surface. These queries use the :operator:`$geoIntersects` operator. -.. example:: +- **Proximity**. MongoDB can query for the points nearest to another + point. Proximity queries use the :operator:`$near` operator. - The following command returns the same results as the - :operator:`$near` in the previous example but with more information: +Geospatial Indexes +------------------ - .. code-block:: javascript +MongoDB provides the following geospatial index types to support the +geospatial queries: - db.runCommand( { geoNear: "places", near: [ -74, 40.74 ] } ) +- :doc:`2dsphere `, which supports: - This operation will return the following output: + - Calculations on a sphere - .. code-block:: javascript + - Both GeoJSON objects and legacy coordinate pairs - { - "ns" : "test.places", - "results" : [ - { - "dis" : 3, - "obj" : { - "_id" : ObjectId(" ... "), - "loc" : [ - -73, - 39 - ] - } - } - ], - "stats" : { - "time" : 2, - "btreelocs" : 0, - "nscanned" : 1, - "objectsLoaded" : 1, - "avgDistance" : 3, - "maxDistance" : 3.0000188685220253 - }, - "near" : "0110000111111000000111111000000111111000000111111000", - "ok" : 1 - } + - A compound index with scalar index fields (i.e. ascending or + descending) as a prefix or suffix of the ``2dsphere`` index field -.. index:: geospatial queries; distance limit -.. _geospatial-indexes-distance: + .. versionadded:: 2.4 + ``2dsphere`` indexes are not available before version 2.4. -Distance Queries -~~~~~~~~~~~~~~~~ +- :doc:`2d `, which supports: -You can limit a proximity query to those documents that fall within a -maximum distance of a point. You specify the maximum distance using the -units specified by the coordinate system. For example, if the coordinate -system uses meters, you specify maximum distance in meters. + - Calculations using flat geometry -To specify distance using the :method:`find() ` -method, use :operator:`$maxDistance` operator. Use the following form: + - Legacy coordinate pairs (i.e., geospatial points on a flat + coordinate system) -.. code-block:: javascript + - A compound index with only one additional field, as a suffix of the + ``2d`` index field - db.collection.find( { : { $near : [ x , y ] , $maxDistance : } } ) +See the following pages for complete documentation of geospatial indexes +and queries: -To specify distance with the :dbcommand:`geoNear` command, use the -``maxDistance`` option. Use the following form: +.. toctree:: + :maxdepth: 1 -.. code-block:: javascript - - db.runCommand( { geoNear: , near: [ x, y ], maxDistance: } ) - -.. _geospatial-indexes-limit: - -Limit the Number of Results -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -By default, geospatial queries using :method:`~db.collection.find()` -method return 100 documents, sorted by distance. To limit the result -when using the :method:`~db.collection.find()` method, use the -:method:`~cursor.limit()` method, as in the following prototype: - -.. code-block:: javascript - - db.collection.find( { : { $near: [ x, y ] } } ).limit() - -To limit the result set when using the :dbcommand:`geoNear` command, use -the ``num`` option. Use the following form: - -.. code-block:: javascript - - db.runCommand( { geoNear: , near: [ x, y ], num: z } ) - -To limit geospatial search results by distance, see -:ref:`geospatial-indexes-distance`. - -.. _geospatial-indexes-within: -.. _geospatial-indexes-bounded: - -Bounded Queries ---------------- - -Bounded queries return documents within a shape defined using the -:operator:`$within` operator. MongoDB's bounded queries support the -following shapes: - -- :ref:`geospatial-indexes-circles` -- :ref:`geospatial-indexes-rectangles` -- :ref:`geospatial-indexes-polygons` - -Bounded queries do not return sorted results. As a result MongoDB can -return bounded queries more quickly than :ref:`proximity queries -`. Bounded queries have the following -form: - -.. code-block:: javascript - - db.collection.find( { : - { "$within" : - { : } - } - } ) - -The following sections describe each of the shapes supported by -bounded queries: - -.. _geospatial-indexes-circles: - -Circles -~~~~~~~ - -To query for documents with coordinates inside the bounds of a circle, -specify the center and the radius of the circle using the -:operator:`$within` operator and :operator:`$center` option. Consider -the following prototype query: - -.. code-block:: javascript - - db.collection.find( { "field": { "$within": { "$center": [ center, radius ] } } } ) - -The following example query returns all documents that have coordinates -that exist within the circle centered on ``[-74, 40.74]`` and with a -radius of ``10``, using a geospatial index on the ``loc`` field: - -.. code-block:: javascript - - db.places.find( { "loc": { "$within": - { "$center": [ [-74, 40.74], 10 ] } - } - } ) - -The :operator:`$within` operator using :operator:`$center` is similar -to using :operator:`$maxDistance`, but :operator:`$center` has -different performance characteristics. MongoDB does not sort queries -that use the :operator:`$within` operator are not sorted, unlike -queries using the :operator:`$near` operator. - -.. _geospatial-indexes-rectangles: - -Rectangles -~~~~~~~~~~ - -To query for documents with coordinates inside the bounds of a -rectangle, specify the lower-left and upper-right corners of the -rectangle using the :operator:`$within` operator and :operator:`$box` -option. Consider the following prototype query: - -.. code-block:: javascript - - db.collection.find( { "field": { "$within": { "$box": [ coordinate0, coordinate1 ] } } } ) - -The following query returns all documents that have coordinates -that exist within the rectangle where the lower-left corner is at -``[ 0, 0 ]`` and the upper-right corner is at ``[ 3, 3 ]``, using a -geospatial index on the ``loc`` field: - -.. code-block:: javascript - - db.places.find( { "loc": { "$within": { "$box": [ [0, 0] , [3, 3] ] } } } ) - -.. _geospatial-indexes-polygons: - -Polygons -~~~~~~~~ - -.. versionadded:: 1.9 - Support for polygon queries. - -To query for documents with coordinates inside of a polygon, specify the points -of the polygon in an array, using the :operator:`$within` operator -with the :operator:`$polygon` option. MongoDB automatically connects the -last point in the array to the first point. Consider the following -prototype query: - -.. code-block:: javascript - - db.places.find({ "loc": { "$within": { "$polygon": [ points ] } } }) - -The following query returns all documents that have coordinates -that exist within the polygon defined by ``[ [0,0], [3,3], [6,0] ]``: - -.. code-block:: javascript - - db.places.find({ "loc": { "$within": { "$polygon": - [ [ 0,0], [3,3], [6,0] ] } } } ) - -.. index:: geospatial queries -.. index:: geospatial queries; exact -.. _geospatial-indexes-exact-match: - -Query for Exact Matches ------------------------ - -You can use the :method:`db.collection.find()` method to query for an -exact match on a location. These queries have the following form: - -.. code-block:: javascript - - db.collection.find( { : [ x, y ] } ) - -This query will return any documents with the value of ``[ x, y ]``. - -Exact geospatial queries only applicability for a limited selection of -cases, the :ref:`proximity ` and -:ref:`bounded ` queries provide more useful -results for more applications. - -.. _geospatial-indexes-spherical: - -Calculate Distances Using Spherical Geometry --------------------------------------------- - -When you query using the ``2d`` index, MongoDB calculates distances -using flat geometry by default, which models points on a flat surface. - -Optionally, you may instruct MongoDB to calculate distances using spherical geometry, which -models points on a spherical surface. Spherical geometry is useful for -modeling coordinates on the surface of Earth. - -To calculate distances using spherical geometry, use MongoDB's -spherical query operators and options: - -- :method:`find() ` method with the - :operator:`$nearSphere` operator. - -- :method:`find() ` method with the - :operator:`$centerSphere`. - -- :dbcommand:`geoNear` command with the ``{ spherical: true }`` option. - -.. seealso:: :ref:`geospatial-query-operators`. - -For more information on differences between flat and spherical distance -calculation, see :ref:`geospatial-indexes-distance-calculation`. - -.. _geospatial-indexes-distance-multiplier: - -Distance Multiplier -------------------- - -The ``distanceMultiplier`` option :dbcommand:`geoNear` returns -distances only after multiplying the results by command by an assigned -value. This allows MongoDB to return converted values, and removes the -requirement to convert units in application logic. - -.. note:: - - Because ``distanceMultiplier`` is an option to - :dbcommand:`geoNear`, the multiplication operation occurs on the - :program:`mongod` process. The operation adds a slight overhead to - the operation of :dbcommand:`geoNear`. - -Using ``distanceMultiplier`` in spherical queries allows one to use -results from the :dbcommand:`geoNear` command without radian to -distance conversion. The following example uses ``distanceMultiplier`` -in the :dbcommand:`geoNear` command with a :ref:`spherical -` example: - -.. code-block:: javascript - - db.runCommand( { geoNear: "places", - near: [ -74, 40.74 ], - spherical: true, - distanceMultiplier: 3963.192 - } ) - -The output of the above operation would resemble the following: - -.. code-block:: javascript - - { - // [ ... ] - "results" : [ - { - "dis" : 73.46525170413567, - "obj" : { - "_id" : ObjectId( ... ) - "loc" : [ - -73, - 40 - ] - } - } - ], - "stats" : { - // [ ... ] - "avgDistance" : 0.01853688938212826, - "maxDistance" : 0.01853714811400047 - }, - "ok" : 1 - } - -.. seealso:: The :ref:`Distance operator `. - -.. _geospatial-indexes-haystack-queries: - -Querying Haystack Indexes -------------------------- - -Haystack indexes are a special ``2d`` geospatial index that optimized -to return results over small areas. To create geospatial indexes see -:ref:`geospatial-indexes-haystack-index`. - -To query the haystack index, use the :dbcommand:`geoSearch` -command. You must specify both the coordinate and other field to -:dbcommand:`geoSearch`, which take the following form: - -.. code-block:: javascript - - db.runCommand( { geoSearch: , - search: { : } } ) - -For example, to return all documents with the value ``restaurants`` in -the ``type`` field near the example point, the command would resemble: - -.. code-block:: javascript - - db.runCommand( { geoSearch: "places", - search: { type: "restaurant" }, - near: [-74, 40.74] } ) - -.. note:: - - Haystack indexes are not suited to returning a full list of the - closest documents to a particular location, as the closest - documents could be far away compared to the ``bucketSize``. - -.. note:: - - :ref:`Spherical query operations ` - are not currently supported by haystack indexes. - - The :method:`find() ` method and - :dbcommand:`geoNear` command cannot access the haystack index. + /applications/2d + /applications/2dsphere + /applications/geohaystack + /reference/geospatial-queries + /tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes + /core/geospatial-indexes diff --git a/source/core/geospatial-indexes.txt b/source/core/geospatial-indexes.txt index 5fb964fbf78..3d03df583e2 100644 --- a/source/core/geospatial-indexes.txt +++ b/source/core/geospatial-indexes.txt @@ -1,345 +1,34 @@ -========================= -``2d`` Geospatial Indexes -========================= +========================== +Geospatial Index Internals +========================== .. default-domain:: mongodb -Overview --------- +This document provides a more in-depth explanation of the internals supporting +geospatial features. This material is not necessary for normal operations +or application development but may be useful for troubleshooting and for +further understanding MongoDB's behavior and approach. -``2d`` geospatial indexes make it possible to associate documents with -locations in two-dimensional space, such as a point on a map. MongoDB -interprets two-dimensional coordinates in a location field as points -and can index these points in a special index type to support -location-based queries. Geospatial indexes provide special geospatial -query operators. For example, you can query for documents based on -proximity to another location or based on inclusion in a specified -region. - -Geospatial indexes support queries on both the coordinate field *and* -another field, such as a type of business or attraction. For example, -you might write a query to find restaurants a specific distance from a -hotel or to find museums within a certain defined neighborhood. - -This document describes how to store location data in your documents -and how to create geospatial indexes. For information on querying data -stored in geospatial indexes, see :doc:`/applications/geospatial-indexes`. - -.. _geospatial-indexes-coordinates: - -Store Location Data -------------------- - -To use ``2d`` geospatial indexes, you must model location data on a -predetermined two-dimensional coordinate system, such as longitude -and latitude. You store a document's location data as two coordinates -in a field that holds either a two-dimensional array or an embedded -document with two fields. Consider the following two examples: - -.. code-block:: javascript - - loc : [ x, y ] - - loc : { x: 1, y: 2 } - -All documents must store location data in the same order. If -you use latitude and longitude as your coordinate system, always store -longitude first. MongoDB's :ref:`2d spherical index operators -` only recognize ``[ longitude, latitude]`` -ordering. - -.. _geospatial-indexes-create: - -Create a Geospatial Index -------------------------- - -.. important:: MongoDB only supports *one* geospatial index per - collection. - -To create a geospatial index, use the :method:`ensureIndex -` method with the value ``2d`` for the -location field of your collection. Consider the following prototype: - -.. code-block:: javascript - - db.collection.ensureIndex( { : "2d" } ) - -MongoDB's :ref:`geospatial operations -` use this index when querying for location -data. - -When you create the index, MongoDB converts location data to binary -:term:`geohash` values and calculates these values using the location -data and the index's location range, as described in -:ref:`geospatial-indexes-range`. The default range for ``2d`` indexes -assumes longitude and latitude and uses the bounds -180 inclusive and -180 non-inclusive. - -.. important:: The default boundaries of ``2d`` indexes allow - applications to insert documents with invalid latitudes greater - than 90 or less than -90. The behavior of geospatial queries with - such invalid points is not defined. - -When creating a ``2d`` index, MongoDB provides the following options: - -.. _geospatial-indexes-range: - -Location Range -~~~~~~~~~~~~~~ - -All ``2d`` geospatial indexes have boundaries defined by a coordinate -range. By default, ``2d`` geospatial indexes assume longitude and -latitude have boundaries of -180 inclusive and 180 non-inclusive -(i.e. ``[-180, 180)``). MongoDB returns an error and rejects documents -with coordinate data outside of the specified range. - -To build an index with a location range other than the -default, use the ``min`` and ``max`` options with the -:method:`ensureIndex() ` operation when -creating a ``2d`` index, as in the following prototype: - -.. code-block:: javascript - - db.collection.ensureIndex( { : "2d" } , - { min: , max: } ) - -.. _geospatial-indexes-precision: - -Location Precision -~~~~~~~~~~~~~~~~~~ - -``2d`` indexes use a :ref:`geohash ` -representation of all coordinate data internally. Geohashes have a -precision that is determined by the number of bits in the hash. More bits -allow the index to provide results with greater precision, while fewer -bits mean the index provides results with more limited -precision. - -Indexes with lower precision have a lower processing overhead for -insert operations and will consume less space. However, higher -precision indexes means that queries will need to scan smaller -portions of the index to return results. The actual stored values are -always used in the final query processing, and index precision does -not affect query accuracy. - -By default, geospatial indexes use 26 bits of precision, which is -roughly equivalent to 2 feet or about 60 centimeters of precision -using the default range of -180 to 180. You can configure ``2d`` -geospatial indexes with up to 32 bits of precision. - -To configure a location precision other than the default, use the -``bits`` option in the :method:`~db.collection.ensureIndex()` method, -as in the following prototype: - -.. code-block:: javascript - - db.collection.ensureIndex( {: "2d"} , - { bits: } ) - -For more information on the relationship between bits and precision, -see :ref:`geospatial-indexes-geohash`. - -Compound Geospatial Indexes -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -``2d`` geospatial indexes may be :ref:`compound -`, if and only if the field with location data is -the first field. A compound geospatial index makes it possible to -construct queries that primarily select on a location-based field but -also select on a second criteria. For example, you could use such -an index to support queries for carpet wholesalers within a specific -region. - -.. note:: Geospatial queries will *only* use additional query - parameters after applying the geospatial criteria. If your - geospatial query criteria selects a large number of - documents, the additional query will only filter the result set - and *not* result in a more targeted query. - -To create a geospatial index with two fields, specify the location field -first, then the second field. For example, to create a compound index on -the ``loc`` location field and on the ``product`` field (sorted in -ascending order), you would issue the following: - -.. code-block:: javascript - - db.storeInfo.ensureIndex( { loc: "2d", product: 1 } ); - -This creates an index that supports queries on just the location field -(i.e. ``loc``), as well as queries on both the ``loc`` and -``product``. - -.. _geospatial-indexes-haystack-index: - -Haystack Indexes -~~~~~~~~~~~~~~~~ - -Haystack indexes create "buckets" of documents from the same geographic -area in order to improve performance for queries limited to that area. - -Each bucket in a haystack index contains all the documents within a -specified proximity to a given longitude and latitude. Use the -``bucketSize`` parameter of :method:`ensureIndex() -` to determine proximity. A -``bucketSize`` of ``5`` creates an index that groups location values -that are within 5 units of the specified longitude and latitude. - -``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 of a two-dimensional -space. Furthermore, the areas defined by buckets can overlap. As a -result a document can exist in multiple buckets. - -To build a haystack index, use the ``bucketSize`` parameter in the -:method:`ensureIndex() ` method, as in the -following prototype: - -.. code-block:: javascript - - db.collection.ensureIndex({ : "geoHaystack", type: 1 }, - { bucketSize: }) - -.. example:: - - Consider a collection with documents that contain fields similar to - the following: - - .. code-block:: javascript - - { _id : 100, pos: { long : 126.9, lat : 35.2 }, type : "restaurant"} - { _id : 200, pos: { long : 127.5, lat : 36.1 }, type : "restaurant"} - { _id : 300, pos: { long : 128.0, lat : 36.7 }, type : "national park"} - - The following operations creates a haystack index with buckets that - store keys within 1 unit of longitude or latitude. - - .. code-block:: javascript - - db.collection.ensureIndex( { pos : "geoHaystack", type : 1 }, { bucketSize : 1 } ) - - Therefore, this index stores the document with an ``_id`` field - that has the value ``200`` in two - different buckets: - - 1. in a bucket that includes the document where the ``_id`` field - has a value of ``100``, and - - 2. in a bucket that includes the document where the ``_id`` field - has a value of ``300``. - -To query using a haystack index you use the :dbcommand:`geoSearch` -command. For command details, see :ref:`geospatial-indexes-haystack-queries`. - -Haystack indexes are ideal for returning documents based on location -*and* an exact match on a *single* additional criteria. These indexes -are not necessarily suited to returning the closest documents to a -particular location. - -:ref:`Spherical queries ` are not -supported by geospatial haystack indexes. - -By default, queries that use a haystack index return 50 documents. - -.. _geospatial-indexes-distance-calculation: - -Distance Calculation --------------------- - -MongoDB performs distance calculations before performing ``2d`` -geospatial queries. By default, MongoDB uses flat geometry to -calculate distances between points. MongoDB also supports distance -calculations using spherical geometry, to provide accurate distances -for geospatial information based on a sphere or earth. - -.. admonition:: Spherical Queries Use Radians for Distance - - For spherical operators to function properly, you must convert - distances to radians, and convert from radians to the distances units - used by your application. - - To convert: - - - *distance to radians*: divide the distance by the radius of the - sphere (e.g. the Earth) in the same units as the distance - measurement. - - - *radians to distance*: multiply the radian measure by the radius - of the sphere (e.g. the Earth) in the units system that you want to - convert the distance to. - - The radius of the Earth is approximately ``3963.192`` miles or - ``6378.137`` kilometers. - -The following query would return documents from the ``places`` -collection within the circle described by the center ``[ -74, 40.74 ]`` -with a radius of ``100`` miles: - -.. code-block:: javascript - - db.places.find( { loc: { $within: { $centerSphere: [ [ -74, 40.74 ] , - 100 / 3963.192 ] } } } ) - -You may also use the ``distanceMultiplier`` option to the -:dbcommand:`geoNear` to convert radians in the :program:`mongod` -process, rather than in your application code. Please see the -:ref:`distance multiplier ` section. - -The following spherical ``2d`` query, returns all documents in the -collection ``places`` within ``100`` miles from the point ``[ -74, -40.74 ]``. - -.. code-block:: javascript - - db.runCommand( { geoNear: "places", - near: [ -74, 40.74 ], - spherical: true - } ) - -The output of the above command would be: - -.. code-block:: javascript - - { - // [ ... ] - "results" : [ - { - "dis" : 0.01853688938212826, - "obj" : { - "_id" : ObjectId( ... ) - "loc" : [ - -73, - 40 - ] - } - } - ], - "stats" : { - // [ ... ] - "avgDistance" : 0.01853688938212826, - "maxDistance" : 0.01853714811400047 - }, - "ok" : 1 - } - -.. warning:: - - Spherical queries that wrap around the poles or at the transition - from ``-180`` to ``180`` longitude raise an error. +Geospatial Indexes and Sharding +------------------------------- -.. note:: +You *cannot* use a geospatial index as a :term:`shard key` when sharding +a collection. However, you can create and maintain a geospatial index on +a sharded collection by using a different field as the shard key. You +can query for geospatial data using :dbcommand:`geoNear` and +:operator:`$geoWithin`. - While the default Earth-like bounds for geospatial indexes are - between ``-180`` inclusive, and ``180``, valid values for latitude - are between ``-90`` and ``90``. +Queries using :operator:`$near` are not supported for sharded +collections. Use :dbcommand:`geoNear` instead. .. _geospatial-indexes-geohash: Geohash Values -------------- -To create a geospatial index, MongoDB computes the :term:`geohash` -value for coordinate pairs within the specified :ref:`range -` and indexes the geohash for that point . +When you create a geospatial index on legacy coordinate pairs, MongoDB computes +:term:`geohash` values for the coordinate pairs within the specified +:ref:`range ` and indexes the geohash values. To calculate a geohash value, continuously divide a 2D map into quadrants. Then assign each quadrant a two-bit value. For example, a @@ -371,45 +60,31 @@ and concatenate the two-bit identifier for each division. The more area that the hash can describe and the higher the resolution of the geospatial index. -Geospatial Indexes and Sharding -------------------------------- - -You *cannot* use a geospatial index as a :term:`shard key` when -sharding a collection. However, you *can* create and maintain a -geospatial index on a sharded collection by using a different field as -the shard key. Your application may query for geospatial data using -:dbcommand:`geoNear` and :operator:`$within`. However, queries using -:operator:`$near` are not supported for sharded collections. - .. _geospatial-indexes-multi-location: -Multi-location Documents ------------------------- +Multi-location Documents for 2D Indexes +--------------------------------------- .. versionadded:: 2.0 Support for multiple locations in a document. -While ``2d`` indexes do not support more than one set of coordinates in -a document, you can use a :ref:`multi-key indexes ` -to store and index multiple coordinate pairs in a single document. In the -simplest example you may have a field (e.g. ``locs``) that holds an -array of coordinates, as in the following prototype data -model: +While ``2d`` geospatial indexes do not support more than one set of +coordinates in a document, you can use a :ref:`multi-key index +` to index multiple coordinate pairs in +a single document. In the simplest example you may have a field (e.g. +``locs``) that holds an array of coordinates, as in the following +example: .. code-block:: javascript - { - "_id": ObjectId(...), - "locs": [ - [ 55.5, 42.3 ], - [ -74, 44.74 ], - { "lat": 55.3, "long": 40.2 } - ] + { _id : ObjectId(...), + locs : [ [ 55.5 , 42.3 ] , + [ -74 , 44.74 ] , + { long : 55.5 , lat : 42.3 } ] } -The values of the array may either be arrays holding coordinates, as -in ``[ 55.5, 42.3 ]``, or embedded documents, as in ``{ "lat": 55.3, -"long": 40.2 }``. +The values of the array may be either arrays, as in ``[ 55.5, 42.3 ]``, +or embedded documents, as in ``{ long : 55.5 , lat : 42.3 }``. You could then create a geospatial index on the ``locs`` field, as in the following: @@ -422,21 +97,19 @@ You may also model the location data as a field inside of a sub-document. In this case, the document would contain a field (e.g. ``addresses``) that holds an array of documents where each document has a field (e.g. ``loc:``) that holds location -coordinates. Consider the following prototype data model: +coordinates. For example: .. code-block:: javascript - { - "_id": ObjectId(...), - "name": "...", - "addresses": [ - { - "context": "home", - "loc": [ 55.5, 42.3 ] - }, + { _id : ObjectId(...), + name : "...", + addresses : [ { + context : "home" , + loc : [ 55.5, 42.3 ] + } , { - "context": "home", - "loc": [ -74, 44.74 ] + context : "home", + loc : [ -74 , 44.74 ] } ] } @@ -451,9 +124,9 @@ in the following example: For documents with multiple coordinate values, queries may return the same document multiple times if more than one indexed coordinate pair satisfies the query constraints. Use the ``uniqueDocs`` parameter to -:dbcommand:`geoNear` or the :operator:`$uniqueDocs` operator in -conjunction with :operator:`$within`. +:dbcommand:`geoNear` or the :operator:`$uniqueDocs` operator with +:operator:`$geoWithin`. -To include the location field with the distance field in -multi-location document queries, specify ``includeLocs: true`` -in the :dbcommand:`geoNear` command. +To include the location field with the distance field in multi-location +document queries, specify ``includeLocs: true`` in the +:dbcommand:`geoNear` command. diff --git a/source/includes/note-geospatial-index-must-exist.rst b/source/includes/note-geospatial-index-must-exist.rst index 77c2b77fc3e..34c66e95e4f 100644 --- a/source/includes/note-geospatial-index-must-exist.rst +++ b/source/includes/note-geospatial-index-must-exist.rst @@ -1,12 +1,6 @@ .. versionchanged:: 2.2.3 - Before 2.2.3, a geospatial index *must* exist on a field holding - coordinates before using any of the geolocation query - operators. After 2.2.3, applications may use geolocation query - operators *without* having a geospatial index; however, geospatial - indexes will support much faster geospatial queries than the - unindexed equivalents. - -.. note:: - - A geospatial index *must* exist on a field and the field must hold coordinates - before you can use any of the geolocation query operators. + Applications can use this operator *without* having a geospatial + index. However, geospatial indexes support much faster queries than + the unindexed equivalents. Before 2.2.3, a geospatial index *must* + exist on a field holding coordinates before using any of the + geospatial query operators. diff --git a/source/includes/table-geospatial-queries.yaml b/source/includes/table-geospatial-queries.yaml new file mode 100644 index 00000000000..3748b2e9ee7 --- /dev/null +++ b/source/includes/table-geospatial-queries.yaml @@ -0,0 +1,174 @@ +# This table is embedded in source/reference/geospatial-queries.txt +# table structure. all content symbolic. +section: layout +header: [ meta.header1, meta.header2, meta.header3, meta.header4, meta.header5 ] +rows: + - 1: [ content.query1, content.geometry1, content.surface1, content.unit1, content.index1 ] + - 2: [ content.query2, content.geometry2, content.surface2, content.unit2, content.index2 ] + - 3: [ content.query3, content.geometry3, content.surface3, content.unit3, content.index3 ] + - 4: [ content.query4, content.geometry4, content.surface4, content.unit4, content.index4 ] + - 5: [ content.query5, content.geometry5, content.surface5, content.unit5, content.index5 ] + - 6: [ content.query6, content.geometry6, content.surface6, content.unit6, content.index6 ] + - 7: [ content.query7, content.geometry7, content.surface7, content.unit7, content.index7 ] + - 8: [ content.query8, content.geometry8, content.surface8, content.unit8, content.index8 ] + - 9: [ content.query9, content.geometry9, content.surface9, content.unit9, content.index9 ] + - 10: [ content.query10, content.geometry10, content.surface10, content.unit10, content.index10 ] +--- +# table metadata, as meta. +section: meta +header1: "Query Document" +header2: "Geometry of the Query Condition" +header3: "Surface Type for Query Calculation" +header4: "Units for Query Calculation" +header5: "Supported by this Index" +--- +# table content, as content. +section: content +query1: | + **Returns points, lines and polygons** +geometry1: | + +surface1: | + +unit1: | + +unit: | + +index1: | + +query2: | + .. code-block:: javascript + + { $geoWithin : { + $geometry : + } } +geometry2: | + polygon +surface2: | + sphere +unit2: | + meters +index2: | + 2dsphere +query3: | + .. code-block:: javascript + + { $geoIntersects : { + $geometry : + } } +geometry3: | + point, line or polygon +surface3: | + sphere +unit3: | + meters +index3: | + 2dsphere +query4: | + .. code-block:: javascript + + { $near : { + $geometry : , + $maxDistance : d + } } +geometry4: | + point +surface4: | + sphere +unit4: | + meters +index4: | + 2dsphere + + The index is required. +query5: | + **Returns points only** +geometry5: | + +surface5: | + +unit5: | + +index5: | + +query6: | + .. code-block:: javascript + + { $geoWithin : { + $box : [[x1, y1], [x2, y2]] + } } +geometry6: | + rectangle +surface6: | + flat +unit6: | + flat units +index6: | + 2d +query7: | + .. code-block:: javascript + + { $geoWithin : { + $polygon : [[x1, y1], + [x1, y2], + [x2, y2], + [x2, y1]] + } } +geometry7: | + polygon +surface7: | + flat +unit7: | + flat units +index7: | + 2d +query8: | + .. code-block:: javascript + + { $geoWithin : { + $center : [x1, y1], + $maxDistance : d + } } +geometry8: | + circular region +surface8: | + flat +unit8: | + flat units +index8: | + 2d +query9: | + .. code-block:: javascript + + { $geoWithin : { + $centerSphere : + [[x, y], radius] + $maxDistance : d + } } +geometry9: | + circular region +surface9: | + sphere +unit9: | + radians +index9: | + 2d + + 2dsphere +query10: | + .. code-block:: javascript + + { $near : [x1, y1], + $maxDistance : d + } +geometry10: | + point +surface10: | + flat / flat units +unit10: | + flat units +index10: | + 2d + + The index is required. +... diff --git a/source/indexes.txt b/source/indexes.txt index 121f7d40208..892cc2b22be 100644 --- a/source/indexes.txt +++ b/source/indexes.txt @@ -13,13 +13,29 @@ and operational concerns, see :doc:`/administration/indexes`. For information on how applications might use indexes, see :doc:`/applications/indexes`. -The following outlines the indexing documentation: +Core MongoDB Indexing Background +-------------------------------- .. toctree:: - :maxdepth: 2 + :maxdepth: 1 core/indexes administration/indexes applications/indexes - applications/geospatial-indexes - core/geospatial-indexes + +Geospatial Indexing +------------------- + +See :doc:`/applications/geospatial-indexes` for an introduction to +geospatial indexing. + +.. toctree:: + :maxdepth: 1 + + /applications/geospatial-indexes + /applications/2d + /applications/2dsphere + /applications/geohaystack + /reference/geospatial-queries + /tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes + /core/geospatial-indexes \ No newline at end of file diff --git a/source/reference/command/geoNear.txt b/source/reference/command/geoNear.txt index 6f0ce07658b..c894b173e4b 100644 --- a/source/reference/command/geoNear.txt +++ b/source/reference/command/geoNear.txt @@ -7,33 +7,48 @@ geoNear .. dbcommand:: geoNear The :dbcommand:`geoNear` command provides an alternative to the - :operator :`$near` operator. In addition to the - functionality of :operator:`$near`, :dbcommand:`geoNear` returns the distance of - each item from the specified point along with additional diagnostic - information. For example: + :operator:`$near` operator. In addition to the functionality of + :operator:`$near`, :dbcommand:`geoNear` returns additional diagnostic + information. + + The :dbcommand:`geoNear` command can use either a :term:`GeoJSON` + point or :term:`legacy coordinate pairs`. + + For a GeoJSON point, use the following syntax: + + .. code-block:: javascript + + db.runCommand( { geoNear : , + near : { type : "Point" , + coordinates: [ ] } , + spherical : true } ) + + For legacy coordinate pairs, use: .. code-block:: javascript - { geoNear : "places" , near : [50,50], num : 10 } + { geoNear : , near : [ ] } - Here, :dbcommand:`geoNear` returns the 10 items nearest to the - coordinates ``[50,50]`` in the collection named - ``places``. `geoNear` provides the following options (specify all - distances in the same units as the document coordinate system:) + `geoNear` provides the following options (specify all + distances in the same units as the document coordinate system): - :field near: Takes the coordinates (e.g. ``[ x, y ]``) to use as - the center of a geospatial query. + :field near: Can use either a GeoJSON point or legacy points, + as shown above. :field num: Optional. Specifies the maximum number of documents to return. The default value is 100. :field maxDistance: Optional. Limits the results to those falling within - a given distance of the center coordinate. + a given distance of the center coordinate. For + :term:`GeoJSON` data distance is in meters. For + :ref:`grid coordinate + ` data + distance is in radians. :field query: Optional. Further narrows the results using any standard - MongoDB query operator or selection. See :method:`db.collection.find()` - and ":doc:`/reference/operators`" for more - information. + MongoDB query operator or selection. See + :method:`db.collection.find()` and + ":doc:`/reference/operators`" for more information. :field spherical: Optional. Default: ``false``. When ``true`` MongoDB will return the query as if the diff --git a/source/reference/geospatial-queries.txt b/source/reference/geospatial-queries.txt new file mode 100644 index 00000000000..6bb27240aa9 --- /dev/null +++ b/source/reference/geospatial-queries.txt @@ -0,0 +1,13 @@ +==================================== +Geospatial Query Compatibility Chart +==================================== + +.. default-domain:: mongodb + +While numerous combinations of query operators are possible, the +following table shows the recommended operators for different types of +queries. The table uses the :operator:`$geoWithin`, :operator:`$geoIntersects` +and :operator:`$near` operators. + +.. include:: /includes/table-geospatial-queries.rst + diff --git a/source/reference/glossary.txt b/source/reference/glossary.txt index 5816f752bc0..22d73cfc19e 100644 --- a/source/reference/glossary.txt +++ b/source/reference/glossary.txt @@ -166,27 +166,6 @@ Glossary more information on the two different approaches to clustering with MongoDB. - polygon - MongoDB's :term:`geospatial` indexes and querying system - allow you to build queries around multi-sided - polygons on two-dimensional coordinate systems. These queries use - the :operator:`$within` operator and a sequence of points that define - the corners of the polygon. - - circle - MongoDB's :term:`geospatial` indexes and querying system - allow you to build queries around circles on two-dimensional - coordinate systems. These queries use the :operator:`$within` operator - and the :operator:`$center` operator to define a circle using the center - and the radius of the circle. - - box - MongoDB's :term:`geospatial` indexes and querying system - allow you to build queries around rectangles on two-dimensional - coordinate systems. These queries use the :operator:`$box` - operator to define a shape using the lower-left - and the upper-right coordinates. - capped collection A fixed-sized :term:`collection `. Once they reach their fixed size, capped collections automatically overwrite @@ -385,6 +364,7 @@ Glossary Data that relates to geographical location. In MongoDB, you may index or store geospatial data according to geographical parameters and reference specific coordinates in queries. + See :doc:`/applications/geospatial-indexes`. checksum A calculated value used to ensure data integrity. @@ -927,3 +907,24 @@ Glossary initial sync The :term:`replica set` operation that replicates data from an existing replica set member to a new or restored replica set member. + + GeoJSON + + GeoJSON is a geospatial data interchange format based on + JavaScript Object Notation (JSON) and is used in geospatial queries. + For details, see the + `GeoJSON Format Specification `_ + + legacy coordinate pairs + The format used for geospatial data prior to MongoDB version 2.4. + This format stores geospatial data as points on a planar + coordinate system. + + datum + A datum is a set of values used to define measurements on the earth. MongoDB's + :doc:`2dsphere index ` uses the WGS84 - SRID 4326 + datum. + + WGS84 + The :term:`datum` MongoDB uses to define measurements in + geospatial queries for locations on the earth. diff --git a/source/reference/operator/box.txt b/source/reference/operator/box.txt index 1d08a7c12fc..139b8dd4903 100644 --- a/source/reference/operator/box.txt +++ b/source/reference/operator/box.txt @@ -8,17 +8,36 @@ $box .. versionadded:: 1.4 - The :operator:`$box` operator specifies a rectangular shape for the - :operator:`$within` operator in :term:`geospatial` queries. To use - the :operator:`$box` operator, you must specify the bottom left and - top right corners of the rectangle in an array object. Consider the - following example: + The :operator:`$box` operator specifies a rectangle for a + :term:`geospatial` :operator:`$geoWithin` query. The query returns + documents that are within the bounds of the rectangle, according to + their point-based location data. The :operator:`$box` operator + returns documents based on :ref:`grid coordinates + ` and does *not* query for + GeoJSON shapes. + + The query calculates distances using flat (planar) geometry. The + ``2d`` geospatial index supports the :operator:`$box` operator. + + To use the :operator:`$box` operator, you must specify the bottom + left and top right corners of the rectangle in an array object. + Use the following syntax: .. code-block:: javascript - db.collection.find( { loc: { $within: { $box: [ [0,0], [100,100] ] } } } ) + { : { $geoWithin : { $box : + [ [ ] , + [ ] ] } } } + + .. important:: If you use longitude and latitude, specify **longitude first**. + + The following example query returns all documents that are within the + box having points at: ``[ 0 , 0 ]``, ``[ 0 , 100 ]``, ``[ 100 , 0 ]``, and ``[ 100 , 100 ]``. + + .. code-block:: javascript - This will return all the documents that are within the box having - points at: ``[0,0]``, ``[0,100]``, ``[100,0]``, and ``[100,100]``. + db.places.find( { loc : { $geoWithin : { $box : + [ [ 0 , 0 ] , + [ 100 , 100 ] ] } } } ) .. include:: /includes/note-geospatial-index-must-exist.rst diff --git a/source/reference/operator/center.txt b/source/reference/operator/center.txt index 6364e293d30..3bff027b746 100644 --- a/source/reference/operator/center.txt +++ b/source/reference/operator/center.txt @@ -8,21 +8,40 @@ $center .. versionadded:: 1.4 - This specifies a circle shape for the :operator:`$within` operator - in :term:`geospatial` queries. To define the bounds of a query - using :operator:`$center`, you must specify: + The :operator:`$center` operator specifies a circle for a + :term:`geospatial` :operator:`$geoWithin` query. The query returns + legacy coordinate pairs that are within the bounds of the circle. The + operator does *not* return GeoJSON objects. - - the center point, and + The query calculates distances using flat (planar) geometry. - - the radius + The ``2d`` geospatial index supports the :operator:`$center` + operator. - Considering the following example: + To use the :operator:`$center` operator, specify an array that + contains: + + - The grid coordinates of the circle's center point + + - The circle's radius, as measured in the units used by the + coordinate system + + .. important:: If you use longitude and latitude, specify **longitude first**. + + Use the following syntax: .. code-block:: javascript - db.collection.find( { location: { $within: { $center: [ [0,0], 10 ] } } } ); + { : { $geoWithin : { $center : [ [ , ] , ] } } } + + The following example query returns all documents that have + coordinates that exist within the circle centered on ``[ -74 , 40.74 ]`` + and with a radius of ``10``: + + .. code-block:: javascript - The above command returns all the documents that fall within a - 10 unit radius of the point ``[0,0]``. + db.places.find( { loc: { $geoWithin : + { $center : [ [-74, 40.74], 10 ] } + } } ) .. include:: /includes/note-geospatial-index-must-exist.rst diff --git a/source/reference/operator/centerSphere.txt b/source/reference/operator/centerSphere.txt index ce74670dd77..df63c152224 100644 --- a/source/reference/operator/centerSphere.txt +++ b/source/reference/operator/centerSphere.txt @@ -8,38 +8,44 @@ $centerSphere .. versionadded:: 1.8 - The :operator:`$centerSphere` operator is the spherical equivalent - of the :operator:`$center` operator. :operator:`$centerSphere` uses - spherical geometry to define a circle for use by the - :operator:`$within` operator in :term:`geospatial` queries. + The :operator:`$centerSphere` operator defines a circle for a + :term:`geospatial` query that uses spherical geometry. The query + returns documents that are within the bounds of the circle. - To define the bounds of a query using :operator:`$centerSphere`, you - must specify: + You can use the :operator:`$centerSphere` operator on both + :term:`GeoJSON` objects and legacy coordinate pairs. - - The center point + The ``2d`` and ``2dsphere`` geospatial indexes both support + :operator:`$centerSphere`. - - The angular distance in radians (distance along the surface of the - earth). + To use :operator:`$centerSphere`, specify an array that contains: - Consider the following prototype: + - The grid coordinates of the circle's center point + + - The circle's radius measured in radians. To calculate radians, see + :doc:`/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes`. + + Use the following syntax: .. code-block:: javascript - db.collection.find( { loc: { $within: - { $centerSphere: - [ [,], / ] - } } } ) + db..find( { : + { $geoWithin : + { $centerSphere : [ [ , ] , ] } + } } ) + + .. important:: If you use longitude and latitude, specify **longitude first**. - The following example returns all documents within a 10 mile radius - of longitude ``88 W`` and latitude ``30 N``. MongoDB converts the - distance, 10 miles, to radians by dividing by the approximate - radius of the earth, 3959 miles: + The following example queries grid coordinates and returns all + documents within a 10 mile radius of longitude ``88 W`` and latitude + ``30 N``. The query converts the distance to radians by dividing by + the approximate radius of the earth, 3959 miles: .. code-block:: javascript - db.collection.find( { loc: { $within: - { $centerSphere: - [ [88,30], 10 / 3959 ] - } } } ) + db.places.find( { loc : { $geoWithin : + { $centerSphere : + [ [ 88 , 30 ] , 10 / 3959 ] + } } } ) .. include:: /includes/note-geospatial-index-must-exist.rst diff --git a/source/reference/operator/geoIntersects.txt b/source/reference/operator/geoIntersects.txt new file mode 100644 index 00000000000..12edee48671 --- /dev/null +++ b/source/reference/operator/geoIntersects.txt @@ -0,0 +1,55 @@ +============== +$geoIntersects +============== + +.. default-domain:: mongodb + +.. operator:: $geoIntersects + + .. versionadded:: 2.4 + + The :operator:`$geoIntersects` operator is a geospatial query + operator that selects all points that intersect with one of the + following :term:`GeoJSON` objects: + + - Point + + - LineString + + - Polygon + + The :operator:`$geoIntersects` operator uses spherical geometry. + + The ``2dsphere`` geospatial index supports + :operator:`$geoIntersects`. + + To query for intersection, pass the GeoJSON object to + :operator:`$geoIntersects` through the :operator:`$geometry` + operator. Use the following syntax: + + .. code-block:: javascript + + db..find( { : + { $geoIntersects : + { $geometry : + { type : "" , + coordinates : [ ] + } } } } ) + + .. important:: Specify coordinates in this order: **"longitude, latitude."** + + The following example uses :operator:`$geoIntersects` to select all + indexed points and shapes that intersect with the polygon defined by + the ``coordinates`` array. + + .. code-block:: javascript + + db.places.find( { loc : + { $geoIntersects : + { $geometry : + { type : "Polygon" , + coordinates: [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ] ] } + } } } } ) + + The query returns true if the intersection between shapes is + non-empty. This includes documents that have a shared edge. diff --git a/source/reference/operator/geoWithin.txt b/source/reference/operator/geoWithin.txt new file mode 100644 index 00000000000..3d1917966e5 --- /dev/null +++ b/source/reference/operator/geoWithin.txt @@ -0,0 +1,97 @@ +========== +$geoWithin +========== + +.. default-domain:: mongodb + +.. operator:: $geoWithin + + .. versionadded:: 2.4 + + The :operator:`$geoWithin` operator is a geospatial query operator + that queries for a defined point, line or shape that exists entirely + within another defined shape. When determining inclusion, MongoDB + considers the border of a shape to be part of the shape (subject to + the precision of floating point numbers). + + The :operator:`$geoWithin` operator queries for inclusion in a + :term:`GeoJSON` polygon or a shape defined by legacy coordinate + pairs. + + The :operator:`$geoWithin` operator does not return sorted results. + As a result MongoDB can return :operator:`$geoWithin` queries more + quickly than geospatial :operator:`$near` or :operator:`$nearSphere` + queries, which sort results. + + The ``2dsphere`` and ``2d`` indexes both support the + :operator:`$geoWithin` operator. + + If querying for inclusion in a GeoJSON polygon on a sphere, pass the + polygon to :operator:`$geoWithin` through the :operator:`$geometry` + operator. Coordinates of a polygon are an array of LinearRing + coordinate arrays. The first element in the array represents the + exterior ring. Any subsequent elements represent interior rings (or + holes). + + For a polygon with only an exterior ring use following syntax: + + .. code-block:: javascript + + db..find( { : + { $geoWithin : + { $geometry : + { type : "Polygon" , + coordinates : [ [ [ , ] , [ , ] ... ] ] + } } } } ) + + .. important:: Specify coordinates in this order: **"longitude, latitude."** + + For a polygon with an exterior and interior ring use following syntax: + + .. code-block:: javascript + + db..find( { : + { $geoWithin : + { $geometry : + { type : "Polygon" , + coordinates : [ [ [ , ] , [ , ] ... ] + [ [ , ] , [ , ] ... ] ] + } } } } ) + + The following example selects all indexed points and shapes that + exist entirely within a GeoJSON polygon: + + .. code-block:: javascript + + db.places.find( { loc : + { $geoWithin : + { $geometry : + { type : "Polygon" , + coordinates: [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ] ] + } } } } ) + + If querying for inclusion in a shape defined by legacy coordinate + pairs on a plane, use the following syntax: + + .. code-block:: javascript + + db..find( { : + { $geoWithin : + { : + } } } ) + + For the syntax for a shape operator, see: + + - :operator:`$box` + + - :operator:`$polygon` + + - :operator:`$center` (defines a circle) + + - :operator:`$centerSphere` (defines a circle on a sphere) + +.. operator:: $within + + .. deprecated:: 2.4 + In 2.4, :operator:`$geoWithin` replaces :operator:`$within`. + \ No newline at end of file diff --git a/source/reference/operator/geometry.txt b/source/reference/operator/geometry.txt new file mode 100644 index 00000000000..9d499ad8129 --- /dev/null +++ b/source/reference/operator/geometry.txt @@ -0,0 +1,19 @@ +========= +$geometry +========= + +.. default-domain:: mongodb + +.. operator:: $geometry + + .. versionadded:: 2.4 + + The :operator:`$geometry` operator specifies a :term:`GeoJSON` for a + geospatial query operators. For details on using + :operator:`$geometry` with an operator, see the operator: + + - :operator:`$geoWithin` + + - :operator:`$geoIntersects` + + - :operator:`$near` diff --git a/source/reference/operator/maxDistance.txt b/source/reference/operator/maxDistance.txt index 9f8f527bd0c..dbebe82b402 100644 --- a/source/reference/operator/maxDistance.txt +++ b/source/reference/operator/maxDistance.txt @@ -6,23 +6,24 @@ $maxDistance .. operator:: $maxDistance - The :operator:`$maxDistance` operator specifies an upper bound to limit - the results of a geolocation query. See below, where the - :operator:`$maxDistance` operator narrows the results of the - :operator:`$near` query: + The :operator:`$maxDistance` operator constrains the results of a + geospatial :operator:`$near` or :operator:`$nearSphere` query to the + specified distance. The measuring units for the maximum distance are + determined by the coordinate system in use. For :term:`GeoJSON` point + object, specify the distance in meters, not radians. - .. code-block:: javascript + The ``2d`` and ``2dsphere`` geospatial indexes both support + :operator:`$maxDistance`. - db.collection.find( { location: { $near: [100,100], $maxDistance: 10 } } ); + The following example query returns documents with location values + that are ``10`` or fewer units from the point ``[ 100 , 100 ]``. - This query will return documents with ``location`` fields from - ``collection`` that have values with a distance of 5 or fewer units - from the point ``[100,100]``. :operator:`$near` returns results - ordered by their distance from ``[100,100]``. This operation will - return the first 100 results unless you modify the query with the - :method:`cursor.limit()` method. + .. code-block:: javascript - Specify the value of the :operator:`$maxDistance` argument in the - same units as the document coordinate system. + db.places.find( { loc : { $near : [ 100 , 100 ] , + $maxDistance: 10 } + } ) - .. include:: /includes/note-geospatial-index-must-exist.rst + MongoDB orders the results by their distance from ``[ 100 , 100 ]``. + The operation returns the first 100 results, unless you modify the + query with the :method:`cursor.limit()` method. diff --git a/source/reference/operator/near.txt b/source/reference/operator/near.txt index 25c75a487f9..02be966df3e 100644 --- a/source/reference/operator/near.txt +++ b/source/reference/operator/near.txt @@ -6,26 +6,79 @@ $near .. operator:: $near - The :operator:`$near` operator takes an argument, coordinates for a - point in the form of ``[x, y]``, and returns a list of objects - sorted by distance from nearest to farthest with respect to those - coordinates. See the following example: + .. versionchanged:: 2.4 + + The :operator:`$near` operator specifies a point for which a + :term:`geospatial` query returns the 100 closest documents. The query + sorts the documents from nearest to farthest. + + The :operator:`$near` operator can query for a :term:`GeoJSON` + point or for a point defined by legacy coordinate pairs. + + The optional :operator:`$maxDistance` operator limits a + :operator:`$near` query to return only those documents that fall + within a maximum distance of a point. If you query for a GeoJSON + point, specify :operator:`$maxDistance` in meters. If you query for + legacy coordinate pairs, specify :operator:`$maxDistance` in radians. + + The :operator:`$near` operator requires a geospatial index. For + GeoJSON points, use a ``2dsphere`` index. For legacy coordinate + pairs, use a ``2d`` index. + + If querying on GeoJSON data, use the following syntax: + + .. code-block:: javascript + + db..find( { : + { $near : + { $geometry : + { type : "Point" , + coordinates : [ , ] } , + $maxDistance : + } } } ) + + .. important:: Specify coordinates in this order: **"longitude, latitude."** + + The following example selects the 100 documents with coordinates + nearest to ``[ 40 , 5 ]`` and limits the maximum distance to 100 + meters from the specified GeoJSON point: .. code-block:: javascript - db.collection.find( { location: { $near: [100,100] } } ); + db.places.find( { loc : { $near : + { $geometry : + { type : "Point" , + coordinates: [ 40 , 5 ] } } , + $maxDistance : 100 + } } } ) - This query will return 100 ordered records with a ``location`` - field in ``collection``. Specify a different limit using the - :method:`cursor.limit()`, or another :ref:`geolocation operator - `, or a non-geospatial operator to limit the - results of the query. + If querying on legacy coordinate pairs, use the following syntax: + + .. code-block:: javascript + + db..find( { : + { $near : [ , ] , + $maxDistance: + } } ) + + .. important:: If you use longitude and latitude, specify **longitude first**. + + The following example selects the 100 documents with coordinates + nearest to ``[ 40 , 5 ]``: + + .. code-block:: javascript + + db.places.find( { loc : + { $near : [ 40 , 5 ] , + $maxDistance : 10 + } } ) .. note:: + You can further limit the number of results using + :method:`cursor.limit()`. + Specifying a batch size (i.e. :method:`batchSize() `) in conjunction with queries that use the :operator:`$near` is not defined. See :issue:`SERVER-5236` for more information. - - .. include:: /includes/note-geospatial-index-must-exist.rst diff --git a/source/reference/operator/nearSphere.txt b/source/reference/operator/nearSphere.txt index 4b700bfc731..1cc7404ac44 100644 --- a/source/reference/operator/nearSphere.txt +++ b/source/reference/operator/nearSphere.txt @@ -8,12 +8,42 @@ $nearSphere .. versionadded:: 1.8 - The :operator:`$nearSphere` operator is the spherical equivalent of - the :operator:`$near` operator. :operator:`$nearSphere` returns all - documents near a point, calculating distances using spherical geometry. + The :operator:`$nearSphere` operator specifies a point for which a + :term:`geospatial` query returns the 100 closest documents. The + :operator:`$nearSphere` operator queries for points defined by legacy + coordinate pairs or :term:`GeoJSON` objects and calculates distances + using spherical geometry. The query sorts the documents from nearest + to farthest. + + The optional :operator:`$maxDistance` operator limits a + :operator:`$nearSphere` query to return only those documents that fall + within a maximum distance of a point. Specify the maximum distance in + the units specified by the coordinate system. + + The :operator:`$nearSphere` operator requires a geospatial index. The + ``2dsphere`` and ``2d`` indexes both support the + :operator:`$nearSphere` operator. In a ``2dsphere`` index, a grid + coordinate is interpreted as a GeoJSON point. + + The :operator:`$nearSphere` operator uses the following syntax: + + .. code-block:: javascript + + db..find( { : + { $nearSphere: [ , ] , + $maxDistance: + } } ) + + .. important:: If you use longitude and latitude, specify **longitude first**. + + The following example selects the 100 documents with coordinates + nearest to ``[ 40 , 5 ]`` as calculated by spherical geometry: .. code-block:: javascript - db.collection.find( { loc: { $nearSphere: [0,0] } } ) + db.places.find( { loc : + { $nearSphere : [ 40 , 5 ] + $maxDistance : 10 + } } ) .. include:: /includes/note-geospatial-index-must-exist.rst diff --git a/source/reference/operator/polygon.txt b/source/reference/operator/polygon.txt index f3b907fbb52..2488faa6e01 100644 --- a/source/reference/operator/polygon.txt +++ b/source/reference/operator/polygon.txt @@ -8,20 +8,40 @@ $polygon .. versionadded:: 1.9 - Use :operator:`$polygon` to specify a polygon for a bounded query - using the :operator:`$within` operator for :term:`geospatial` - queries. To define the polygon, you must specify an array of - coordinate points, as in the following: + The :operator:`$polygon` operator specifies a polygon for a + :term:`geospatial` :operator:`$geoWithin` query. The query returns + legacy coordinate pairs that are within the bounds of the polygon. + The operator does *not* query for GeoJSON objects. - [ [ x1,y1 ], [x2,y2], [x3,y3] ] + The :operator:`$polygon` operator calculates distances using flat (planar) + geometry. + + The ``2d`` geospatial index supports the :operator:`$polygon` + operator. + + To define the polygon, specify an array of coordinate points. Use the + following syntax: + + .. code-block:: javascript + + { : { $geoWithin : { $polygon : [ [ , ] , + [ , ] , + [ , ] ] } } } + + .. important:: If you use longitude and latitude, specify **longitude first**. The last point specified is always implicitly connected to the first. You can specify as many points, and therefore sides, as you - like. Consider the following bounded query for documents with - coordinates within a polygon: + like. + + The following query returns all documents that have coordinates that + exist within the polygon defined by ``[ 0 , 0 ]``, ``[ 3 , 3 ]``, and + ``[ 6 , 0 ]``: .. code-block:: javascript - db.collection.find( { loc: { $within: { $polygon: [ [0,0], [3,6], [6,0] ] } } } ) + db.places.find( { loc : { $geoWithin : { $polygon : [ [ 0 , 0 ] , + [ 3 , 6 ] , + [ 6 , 0 ] ] } } } ) .. include:: /includes/note-geospatial-index-must-exist.rst diff --git a/source/reference/operator/uniqueDocs.txt b/source/reference/operator/uniqueDocs.txt index ecf71db95f2..645d1f1a013 100644 --- a/source/reference/operator/uniqueDocs.txt +++ b/source/reference/operator/uniqueDocs.txt @@ -8,40 +8,36 @@ $uniqueDocs .. versionadded:: 2.0 - For :term:`geospatial` queries, MongoDB may return a single - document more than once for a single query, because geospatial - indexes may include multiple coordinate pairs in a single - document, and therefore return the same document more than once. + The :operator:`$uniqueDocs` operator returns a document only once for + a :term:`geospatial` query if the document matches the query multiple + times. A document might match a query multiple times if the documents + contains multiple coordinate values. - The :operator:`$uniqueDocs` operator inverts the default behavior - of the :operator:`$within` operator. By default, the - :operator:`$within` operator returns the document only once. If you - specify a value of ``false`` for :operator:`$uniqueDocs`, MongoDB - will return multiple instances of a single document. + You can use :operator:`$uniqueDocs` only with the + :operator:`$geoWithin` and :operator:`$geoWithin` operators. The + ``2d`` geospatial index supports :operator:`$uniqueDocs`. .. example:: - Given an ``addressBook`` collection with a document in the following form: + Given a collection of addresses with documents in the following + form: .. code-block:: javascript - { addresses: [ { name: "Home", loc: [55.5, 42.3] }, { name: "Work", loc: [32.3, 44.2] } ] } + { addrs : [ { name : "H" , loc : [ 55.5 , 42.3 ] } , { name : "W" , loc : [ 32.3 , 44.2 ] } ] } - The following query would return the same document multiple - times: + The following query would return the same document multiple times: .. code-block:: javascript - db.addressBook.find( { "addresses.loc": { "$within": { "$box": [ [0,0], [100,100] ], $uniqueDocs: false } } } ) + db.list.find( { addrs.loc : { $geoWithin : { $box : [ [ 0 , 0 ] , [ 100 , 100 ] ] } } } ) - The following query would return each matching document, only - once: + The following query would return each matching document only once: .. code-block:: javascript - db.addressBook.find( { "address.loc": { "$within": { "$box": [ [0,0], [100,100] ], $uniqueDocs: true } } } ) + db.list.find( { addrs.loc : { $geoWithin : { $box : [ [ 0 , 0 ] , [ 100 , 100 ] ], $uniqueDocs: true } } } ) - You cannot specify :operator:`$uniqueDocs` with :operator:`$near` - or haystack queries. - - .. include:: /includes/note-geospatial-index-must-exist.rst + .. note:: If you specify a value of ``false`` for + :operator:`$uniqueDocs`, MongoDB will return multiple instances of + a single document. diff --git a/source/reference/operator/within.txt b/source/reference/operator/within.txt deleted file mode 100644 index 37bb3e2ca71..00000000000 --- a/source/reference/operator/within.txt +++ /dev/null @@ -1,59 +0,0 @@ -======= -$within -======= - -.. default-domain:: mongodb - -.. operator:: $within - - The :operator:`$within` operator allows you to select items that exist - within a shape on a coordinate system for :term:`geospatial` queries. This operator uses the - following syntax: - - .. code-block:: javascript - - db.collection.find( { location: { $within: { shape } } } ); - - Replace ``{ shape }`` with a document that describes a shape. The - :operator:`$within` command supports the following shapes. These shapes and the - relevant expressions follow: - - - Rectangles. Use the :operator:`$box` operator, consider the following - variable and :operator:`$within` document: - - .. code-block:: javascript - - db.collection.find( { location: { $within: { $box: [[100,0], [120,100]] } } } ); - - Here a box, ``[[100,120], [100,0]]`` describes the parameter - for the query. As a minimum, you must specify the lower-left and - upper-right corners of the box. - - - Circles. Use the :operator:`$center` operator. Specify circles in the following form: - - .. code-block:: javascript - - db.collection.find( { location: { $within: { $center: [ center, radius } } } ); - - - Circular distance on a sphere. Use the - :operator:`$centerSphere` operator. For the syntax, see :operator:`$centerSphere`. - - - Polygons. Use the :operator:`$polygon` operator. Specify polygons with an array of points. See the - following example: - - .. code-block:: javascript - - db.collection.find( { location: { $within: { $polygon: [[100,120], [100,100], [120,100], [240,200]] } } } ); - - The last point of a polygon is implicitly connected to the first - point. - - All shapes include the border of the shape as part of the shape, - although this is subject to the imprecision of floating point - numbers. - - Use :operator:`$uniqueDocs` to control whether documents with - many location fields show up multiple times when more than one - of its fields match the query. - - .. include:: /includes/note-geospatial-index-must-exist.rst diff --git a/source/reference/operators.txt b/source/reference/operators.txt index 915c1eaead7..4a4069c813a 100644 --- a/source/reference/operators.txt +++ b/source/reference/operators.txt @@ -101,22 +101,21 @@ JavaScript Geospatial ~~~~~~~~~~ +Operators: + +- :operator:`$geoWithin` +- :operator:`$geoIntersects` - :operator:`$near` -- :operator:`$within` - :operator:`$nearSphere` -Use the following operators within the context of -:operator:`$near`: +Parameters: +- :operator:`$geometry` - :operator:`$maxDistance` - -Use the following operators within the context of -:operator:`$within`: - - :operator:`$center` +- :operator:`$centerSphere` - :operator:`$box` - :operator:`$polygon` -- :operator:`$centerSphere` - :operator:`$uniqueDocs` .. index:: query selectors; array diff --git a/source/release-notes.txt b/source/release-notes.txt index c25c0252df4..0ffc7036d8d 100644 --- a/source/release-notes.txt +++ b/source/release-notes.txt @@ -43,6 +43,7 @@ Current Development Series :maxdepth: 1 /release-notes/2.4 + /release-notes/2.4-upgrade Other MongoDB Release Notes ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/source/release-notes/2.4-javascript.txt b/source/release-notes/2.4-javascript.txt deleted file mode 100644 index 0352d78a0c3..00000000000 --- a/source/release-notes/2.4-javascript.txt +++ /dev/null @@ -1,438 +0,0 @@ -================================= -JavaScript Changes in MongoDB 2.4 -================================= - -.. default-domain:: mongodb - -Consider the following impacts of :ref:`rn-2.4-javascript-change` in -MongoDB 2.4: - -Improved Concurrency --------------------- - -Previously, MongoDB operations that required the JavaScript interpreter -had to acquire a lock, and a single :program:`mongod` could only run a -single JavaScript operation at a time. The switch to V8 improves -concurrency by permiting multiple JavaScript operations to run at the -same time. - -Modernized JavaScript Implementation (ES5) ------------------------------------------- - -The 5th edition of `ECMAscript -`_, -abbreviated as ES5, adds many new language features, including: - -- standardized `JSON - `_, - -- `strict mode - `_, - -- `function.bind() - `_, - -- `array extensions - `_, and - -- getters and setters. - -With V8, MongoDB supports the ES5 implementation of Javascript with the -following exceptions. - -.. note:: - - The following features do not work as expected on documents - **returned from MongoDB queries**: - - - ``Object.seal()`` throws an exception on documents returned from - MongoDB queries. - - - ``Object.freeze()`` throws an exception on documents returned from - MongoDB queries. - - - ``Object.preventExtensions()`` incorrectly allows the addition of - new properties on documents returned from MongoDB queries. - - - ``enumerable`` properties, when added to documents returned from - MongoDB queries, are not saved during write operations. - - See :issue:`SERVER-8216`, :issue:`SERVER-8223`, - :issue:`SERVER-8215`, and :issue:`SERVER-8214` for more information. - - For objects that have not been returned from MongoDB queries, the - features work as expected. - -Removed Non-Standard SpiderMonkey Features ------------------------------------------- - -V8 does **not** support the following *non-standard* `SpiderMonkey -`_ JavaScript -extensions, previously supported by MongoDB's use of SpiderMonkey as -its JavaScript engine. - -E4X Extensions -~~~~~~~~~~~~~~ - -V8 does not support the *non-standard* `E4X -`_ extensions. E4X -provides a native `XML -`_ -object to the JavaScript language and adds the syntax for embedding -literal XML documents in JavaScript code. - -You need to use alternative XML processing if you used any of the -following constructors/methods: - -- ``XML()`` - -- ``Namespace()`` - -- ``QName()`` - -- ``XMLList()`` - -- ``isXMLName()`` - -Destructuring Assignment -~~~~~~~~~~~~~~~~~~~~~~~~ - -V8 does not support the non-standard destructuring assignments. -Destructuring assignment "extract[s] data from arrays or objects using -a syntax that mirrors the construction of array and object literals." - -`Mozilla docs -`_ - -.. example:: - - The following destructuring assignment is **invalid** with V8 and - throws a ``SyntaxError``: - - .. code-block:: javascript - - original = [4, 8, 15]; - var [b, ,c] = a; // <== destructuring assignment - print(b) // 4 - print(c) // 15 - -``Iterator()``, ``StopIteration()``, and Generators -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -V8 does not support `Iterator(), StopIteration(), and generators -`_. - -``InternalError()`` -~~~~~~~~~~~~~~~~~~~ - -V8 does not support ``InternalError()``. Use ``Error()`` instead. - -``for each...in`` Construct -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -V8 does not support the use of `for each...in -`_ -construct. Use ``for (var x in y)`` construct -instead. - -.. example:: - - The following ``for each (var x in y)`` construct is **invalid** - with V8: - - .. code-block:: javascript - - var o = { name: 'MongoDB', version: 2.4 }; - - for each (var value in o) { - print(value); - } - - Instead, in version 2.4, you can use the ``for (var x in y)`` - construct: - - .. code-block:: javascript - - var o = { name: 'MongoDB', version: 2.4 }; - - for (var prop in o) { - var value = o[prop]; - print(value); - } - - You can also use the array *instance* method ``forEach()`` with the - ES5 method ``Object.keys()``: - - .. code-block:: javascript - - Object.keys(o).forEach(function (key) { - var value = o[key]; - print(value); - }); - -Array Comprehension -~~~~~~~~~~~~~~~~~~~ - -V8 does not support `Array comprehensions -`_. - -Use other methods such as the ``Array`` instance methods ``map()``, -``filter()``, or ``forEach()``. - -.. example:: - - With V8, the following array comprehension is **invalid**: - - .. code-block:: javascript - - var a = { w: 1, x: 2, y: 3, z: 4 } - - var arr = [i * i for each (i in a) if (i > 2)] - printjson(arr) - - Instead, you can implement using the ``Array`` *instance* method - ``forEach()`` and the ES5 method ``Object.keys()`` : - - .. code-block:: javascript - - var a = { w: 1, x: 2, y: 3, z: 4 } - - var arr = []; - Object.keys(a).forEach(function (key) { - var val = a[key]; - if (val > 2) arr.push(val * val); - }) - printjson(arr) - - .. note:: - - The new logic uses the ``Array`` *instance* method ``forEach()`` and - not the *generic* method ``Array.forEach()``; V8 does **not** - support ``Array`` *generic* methods. See :ref:`array-generics` for - more information. - -Multiple Catch Blocks -~~~~~~~~~~~~~~~~~~~~~ - -V8 does not support multiple ``catch`` blocks and will throw a -``SyntaxError``. - -.. example:: - - The following multiple catch blocks is **invalid** with V8 and will - throw ``"SyntaxError: Unexpected token if"``: - - .. code-block:: javascript - - try { - something() - } catch (err if err instanceof SomeError) { - print('some error') - } catch (err) { - print('standard error') - } - -Conditional Function Definition -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -V8 will produce different outcomes than SpiderMonkey with `conditional -function definitions -`_. - -.. example:: - - The following conditional function definition produces different - outcomes in SpiderMonkey versus V8: - - .. code-block:: javascript - - function test () { - if (false) { - function go () {}; - } - print(typeof go) - } - - With SpiderMonkey, the conditional function outputs ``undefined``, - whereas with V8, the conditional function outputs ``function``. - - If your code defines functions this way, it is highly recommended - that you refactor the code. The following example refactors the - conditional function definition to work in both SpiderMonkey and V8. - - .. code-block:: javascript - - function test () { - var go; - if (false) { - go = function () {} - } - print(typeof go) - } - - The refactored code outputs ``undefined`` in both SpiderMonkey and V8. - -.. note:: - - ECMAscript prohibits conditional function definitions. To force V8 - to throw an ``Error``, `enable strict mode - `_. - - .. code-block:: javascript - - function test () { - 'use strict'; - - if (false) { - function go () {} - } - } - - The JavaScript code throws the following syntax error: - - .. code-block:: none - - SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function. - -String Generic Methods -~~~~~~~~~~~~~~~~~~~~~~ - -V8 does not support `String generics -`_. -String generics are a set of methods on the ``String`` class that -mirror instance methods. - -.. example:: - - The following use of the generic method - ``String.toLowerCase()`` is **invalid** with V8: - - .. code-block:: javascript - - var name = 'MongoDB'; - - var lower = String.toLowerCase(name); - - With V8, use the ``String`` instance method ``toLowerCase()`` available - through an *instance* of the ``String`` class instead: - - .. code-block:: javascript - - var name = 'MongoDB'; - - var lower = name.toLowerCase(); - print(name + ' becomes ' + lower); - -With V8, use the ``String`` *instance* methods instead of following -*generic* methods: - -.. list-table:: - - * - ``String.charAt()`` - - ``String.quote()`` - - ``String.toLocaleLowerCase()`` - - * - ``String.charCodeAt()`` - - ``String.replace()`` - - ``String.toLocaleUpperCase()`` - - * - ``String.concat()`` - - ``String.search()`` - - ``String.toLowerCase()`` - - * - ``String.endsWith()`` - - ``String.slice()`` - - ``String.toUpperCase()`` - - * - ``String.indexOf()`` - - ``String.split()`` - - ``String.trim()`` - - * - ``String.lastIndexOf()`` - - ``String.startsWith()`` - - ``String.trimLeft()`` - - * - ``String.localeCompare()`` - - ``String.substr()`` - - ``String.trimRight()`` - - * - ``String.match()`` - - ``String.substring()`` - - - -.. _array-generics: - -Array Generic Methods -~~~~~~~~~~~~~~~~~~~~~ - -V8 does not support `Array generic methods -`_. -Array generics are a set of methods on the ``Array`` class that mirror -instance methods. - -.. example:: - - The following use of the generic method ``Array.every()`` is - **invalid** with V8: - - .. code-block:: javascript - - var arr = [4, 8, 15, 16, 23, 42]; - - function isEven (val) { - return 0 === val % 2; - } - - var allEven = Array.every(arr, isEven); - print(allEven); - - With V8, use the ``Array`` instance method ``every()`` available through - an *instance* of the ``Array`` class instead: - - .. code-block:: javascript - - var allEven = arr.every(isEven); - print(allEven); - -With V8, use the ``Array`` *instance* methods instead of the following -*generic* methods: - -.. list-table:: - - * - ``Array.concat()`` - - ``Array.lastIndexOf()`` - - ``Array.slice()`` - - * - ``Array.every()`` - - ``Array.map()`` - - ``Array.some()`` - - * - ``Array.filter()`` - - ``Array.pop()`` - - ``Array.sort()`` - - * - ``Array.forEach()`` - - ``Array.push()`` - - ``Array.splice()`` - - * - ``Array.indexOf()`` - - ``Array.reverse()`` - - ``Array.unshift()`` - - * - ``Array.join()`` - - ``Array.shift()`` - - - -Array Instance Method ``toSource()`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -V8 does not support the ``Array`` instance method `toSource() -`_. -Use the ``Array`` instance method ``toString()`` instead. - -``uneval()`` -~~~~~~~~~~~~ - -V8 does not support the non-standard method ``uneval()``. Use the -standardized `JSON.stringify() -`_ -method instead. diff --git a/source/release-notes/2.4.txt b/source/release-notes/2.4.txt index 1b71fdeed5a..8dadd0a9028 100644 --- a/source/release-notes/2.4.txt +++ b/source/release-notes/2.4.txt @@ -11,14 +11,14 @@ candidate builds, are for *testing only and not for production use*. This document will eventually contain the full release notes for -MongoDB 2.4; before its release this document covers the 2.3 -development series as a work-in-progress. +MongoDB 2.4; before its release this document covers the 2.3.x +development branch as a work-in-progress. .. contents:: See the :doc:`full index of this page <2.4-changes>` for a complete list of changes included in 2.4. :backlinks: none :local: - :depth: 3 + :depth: 2 Downloading ----------- @@ -37,19 +37,11 @@ process. Upgrade Process --------------- -.. toctree:: - :hidden: - - /release-notes/2.4-upgrade - See :doc:`/release-notes/2.4-upgrade` for full upgrade instructions. Changes ------- -Major Features -++++++++++++++ - Text Indexes ~~~~~~~~~~~~ @@ -546,108 +538,636 @@ The ``text`` index and the :dbcommand:`text` command support the following languages: - ``danish`` + - ``dutch`` + - ``english`` + - ``finnish`` + - ``french`` + - ``german`` + - ``hungarian`` + - ``italian`` + - ``norwegian`` + - ``portuguese`` + - ``romanian`` + - ``russian`` + - ``spanish`` + - ``swedish`` + - ``turkish`` -New Geospatial Indexes with GeoJSON and Improved Spherical Geometry -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +.. _kerberos-authentication: + +New Modular Authentication System with Support for Kerberos +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. note:: - In 2.3.2, the index type for Spherical Geospatial Indexes - become ``2dsphere``. + Kerberos authentication is only present in the `MongoDB Subscriber + Edition `_. + To download the 2.4.0 release candidate the Subscriber Edition, use + the following resources: -The 2.3 series adds a new type of geospatial index that supports -improved spherical queries and GeoJSON. Create the index by specifying -``2dsphere`` as the value of the field in the index specification, as -any of the following: + - `Amazon Linux 6.4 `_ + - `Red Hat Enterprise Linux 6.2 `_ + - `Ubuntu 11.04 `_ + - `SUSE 11 `_ -.. code-block:: javascript +In 2.4 the MongoDB Subscriber edition now supports authentication via +a Kerberos mechanism. See +:doc:`/tutorial/control-access-to-mongodb-with-kerberos-authentication` +for more information. - db.collection.ensureIndex( { geo: "2dsphere" } ) - db.collection.ensureIndex( { type: 1, geo: "2dsphere" } ) - db.collection.ensureIndex( { geo: "2dsphere", type: 1 } ) +Also consider the following documents that address authenticating to +MongoDB using Kerberos: -In the first example you create a spherical geospatial index on the -field named ``geo``, in the second example, you create a compound -index where the first field is a normal index, and the index of the -second field is a spherical geospatial index. Unlike ``2d`` indexes, -fields indexed using the ``2dsphere`` type do not have to be the first -field in a compound index. +- :ecosystem:`Authenticate to MongoDB using Kerberos and the Java + Driver ` -You must store data in the fields indexed using the ``2dsphere`` index -using the `GeoJSON`_ specification, at the moment. Support for storing -points, in the form used by the existing ``2d`` (i.e. geospatial) -indexes is forthcoming. Currently, ``2dsphere`` indexes only support -the following GeoJSON shapes: +- :ecosystem:`Authenticate to MongoDB using Kerberos and the C# Driver + ` -- ``Point``, as in the following: +.. see:: :doc:`MongoDB Security Practices and Procedures `. - .. code-block:: javascript +Role Based Access Control and New Privilege Documents +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - { "type": "Point", "coordinates": [ 40, 5 ] } +MongoDB 2.4 introduces a role based access control system that +provides more granular privileges to MongoDB users. See +:doc:`/reference/user-privileges` for more information. + +To support the new access control system, 2.4 also introduces a new +format for documents in a database's :data:`system.user +<.system.user>` collection. See +:doc:`/reference/privilege-documents` for more information. -- ``LineString``, as in the following: +Use :parameter:`supportCompatibilityFormPrivilegeDocuments` to disable +the legacy privilege documents, which MongoDB continues to support in +2.4. - .. code-block:: javascript +Default JavaScript Engine Switched to V8 from SpiderMonkey +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - { "type": "LineString", "coordinates": [ [ 40, 5 ], [ 41, 6 ] ] } +The default JavaScript engine used throughout MongoDB, for the +:program:`mongo` shell, :dbcommand:`mapReduce`, :operator:`$where`, +:dbcommand:`group`, and :dbcommand:`eval` is now `V8 +`_. -- ``Polygon``, as in the following: +.. data:: serverBuildInfo.interpreterVersion - .. code-block:: javascript + The :data:`interpreterVersion` field of the document output by + :method:`db.serverBuildInfo()` in the :program:`mongo` shell + reports which JavaScript interpreter the :program:`mongod` instance + is running. + +.. method:: interpreterVersion() + + The :method:`interpreterVersion()` in the :program:`mongo` shell + reports which JavaScript interpreter this :program:`mongo` shell + uses. + +.. DOCS-981 + +The primary impacts of the switch to V8 are: + +- concurrency improvements, +- modernized JavaScript implementation, and +- removal of non-standard SpiderMonkey features. + +Improved Concurrency +```````````````````` + +Previously, MongoDB operations that required the JavaScript interpreter +had to acquire a lock, and a single :program:`mongod` could only run a +single JavaScript operation at a time. The switch to V8 improves +concurrency by permiting multiple JavaScript operations to run at the +same time. + +Modernized JavaScript Implementation (ES5) +`````````````````````````````````````````` + +The 5th edition of `ECMAscript +`_, +abbreviated as ES5, adds many new language features, including: + +- standardized `JSON + `_, + +- `strict mode + `_, + +- `function.bind() + `_, + +- `array extensions + `_, and + +- getters and setters. + +With V8, MongoDB supports the ES5 implementation of Javascript with the +following exceptions. + +.. note:: + + The following features do not work as expected on documents + **returned from MongoDB queries**: + + - ``Object.seal()`` throws an exception on documents returned from + MongoDB queries. + + - ``Object.freeze()`` throws an exception on documents returned from + MongoDB queries. + + - ``Object.preventExtensions()`` incorrectly allows the addition of + new properties on documents returned from MongoDB queries. + + - ``enumerable`` properties, when added to documents returned from + MongoDB queries, are not saved during write operations. + + See :issue:`SERVER-8216`, :issue:`SERVER-8223`, + :issue:`SERVER-8215`, and :issue:`SERVER-8214` for more information. + + For objects that have not been returned from MongoDB queries, the + features work as expected. + +Removed Non-Standard SpiderMonkey Features +`````````````````````````````````````````` + +V8 does **not** support the following *non-standard* `SpiderMonkey +`_ JavaScript +extensions, previously supported by MongoDB's use of SpiderMonkey as +its JavaScript engine. + +E4X Extensions +^^^^^^^^^^^^^^ + +V8 does not support the *non-standard* `E4X +`_ extensions. E4X +provides a native `XML +`_ +object to the JavaScript language and adds the syntax for embedding +literal XML documents in JavaScript code. + +You need to use alternative XML processing if you used any of the +following constructors/methods: + +- ``XML()`` + +- ``Namespace()`` + +- ``QName()`` + +- ``XMLList()`` + +- ``isXMLName()`` + +Destructuring Assignment +^^^^^^^^^^^^^^^^^^^^^^^^ + +V8 does not support the non-standard destructuring assignments. +Destructuring assignment "extract[s] data from arrays or objects using +a syntax that mirrors the construction of array and object literals." - +`Mozilla docs +`_ + +.. example:: + + The following destructuring assignment is **invalid** with V8 and + throws a ``SyntaxError``: + + .. code-block:: javascript + + original = [4, 8, 15]; + var [b, ,c] = a; // <== destructuring assignment + print(b) // 4 + print(c) // 15 + +``Iterator()``, ``StopIteration()``, and Generators +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +V8 does not support `Iterator(), StopIteration(), and generators +`_. + +``InternalError()`` +^^^^^^^^^^^^^^^^^^^ + +V8 does not support ``InternalError()``. Use ``Error()`` instead. + +``for each...in`` Construct +^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +V8 does not support the use of `for each...in +`_ +construct. Use ``for (var x in y)`` construct +instead. + +.. example:: + + The following ``for each (var x in y)`` construct is **invalid** + with V8: + + .. code-block:: javascript + + var o = { name: 'MongoDB', version: 2.4 }; + + for each (var value in o) { + print(value); + } + + Instead, in version 2.4, you can use the ``for (var x in y)`` + construct: - { - "type": "Polygon", - "coordinates": [ [ [ 40, 5 ], [ 40, 6 ], [ 41, 6 ], [ 41, 5 ], [ 40, 5 ] ] ] - } + .. code-block:: javascript + + var o = { name: 'MongoDB', version: 2.4 }; + + for (var prop in o) { + var value = o[prop]; + print(value); + } + + You can also use the array *instance* method ``forEach()`` with the + ES5 method ``Object.keys()``: + + .. code-block:: javascript + + Object.keys(o).forEach(function (key) { + var value = o[key]; + print(value); + }); + +Array Comprehension +^^^^^^^^^^^^^^^^^^^ + +V8 does not support `Array comprehensions +`_. + +Use other methods such as the ``Array`` instance methods ``map()``, +``filter()``, or ``forEach()``. + +.. example:: + + With V8, the following array comprehension is **invalid**: + + .. code-block:: javascript + + var a = { w: 1, x: 2, y: 3, z: 4 } + + var arr = [i * i for each (i in a) if (i > 2)] + printjson(arr) + + Instead, you can implement using the ``Array`` *instance* method + ``forEach()`` and the ES5 method ``Object.keys()`` : + + .. code-block:: javascript + + var a = { w: 1, x: 2, y: 3, z: 4 } + + var arr = []; + Object.keys(a).forEach(function (key) { + var val = a[key]; + if (val > 2) arr.push(val * val); + }) + printjson(arr) -To query ``2dsphere`` indexes, all current geospatial :ref:`query operators -` with an additional -:operator:`$geoIntersects` operator. Currently, all queries using the -``2dsphere`` index must pass the query selector (e.g. :operator:`$near`, -:operator:`$geoIntersects`) a GeoJSON document. With the exception of the -GeoJSON requirement, the operation of :operator:`$near` is the same -for ``2dsphere`` indexes as ``2d`` indexes. + .. note:: -.. operator:: $geoIntersects + The new logic uses the ``Array`` *instance* method ``forEach()`` and + not the *generic* method ``Array.forEach()``; V8 does **not** + support ``Array`` *generic* methods. See :ref:`array-generics` for + more information. + +Multiple Catch Blocks +^^^^^^^^^^^^^^^^^^^^^ + +V8 does not support multiple ``catch`` blocks and will throw a +``SyntaxError``. + +.. example:: + + The following multiple catch blocks is **invalid** with V8 and will + throw ``"SyntaxError: Unexpected token if"``: + + .. code-block:: javascript + + try { + something() + } catch (err if err instanceof SomeError) { + print('some error') + } catch (err) { + print('standard error') + } + +Conditional Function Definition +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +V8 will produce different outcomes than SpiderMonkey with `conditional +function definitions +`_. + +.. example:: + + The following conditional function definition produces different + outcomes in SpiderMonkey versus V8: + + .. code-block:: javascript + + function test () { + if (false) { + function go () {}; + } + print(typeof go) + } + + With SpiderMonkey, the conditional function outputs ``undefined``, + whereas with V8, the conditional function outputs ``function``. + + If your code defines functions this way, it is highly recommended + that you refactor the code. The following example refactors the + conditional function definition to work in both SpiderMonkey and V8. + + .. code-block:: javascript + + function test () { + var go; + if (false) { + go = function () {} + } + print(typeof go) + } + + The refactored code outputs ``undefined`` in both SpiderMonkey and V8. + +.. note:: + + ECMAscript prohibits conditional function definitions. To force V8 + to throw an ``Error``, `enable strict mode + `_. + + .. code-block:: javascript + + function test () { + 'use strict'; + + if (false) { + function go () {} + } + } + + The JavaScript code throws the following syntax error: + + .. code-block:: none + + SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function. + +String Generic Methods +^^^^^^^^^^^^^^^^^^^^^^ + +V8 does not support `String generics +`_. +String generics are a set of methods on the ``String`` class that +mirror instance methods. + +.. example:: - The :operator:`$geoIntersects` selects all indexed points that - intersect with the provided geometry. (i.e. ``Point``, ``LineString``, - and ``Polygon``.) You must pass :operator:`$geoIntersects` a document - in GeoJSON format. + The following use of the generic method + ``String.toLowerCase()`` is **invalid** with V8: .. code-block:: javascript - db.collection.find( { loc: { $geoIntersects: - { $geometry: { "type": "Point", - "coordinates": [ 40, 5 ] - } } } } ) + var name = 'MongoDB'; + + var lower = String.toLowerCase(name); + + With V8, use the ``String`` instance method ``toLowerCase()`` available + through an *instance* of the ``String`` class instead: + + .. code-block:: javascript + + var name = 'MongoDB'; + + var lower = name.toLowerCase(); + print(name + ' becomes ' + lower); + +With V8, use the ``String`` *instance* methods instead of following +*generic* methods: + +.. list-table:: + + * - ``String.charAt()`` + - ``String.quote()`` + - ``String.toLocaleLowerCase()`` + + * - ``String.charCodeAt()`` + - ``String.replace()`` + - ``String.toLocaleUpperCase()`` + + * - ``String.concat()`` + - ``String.search()`` + - ``String.toLowerCase()`` + + * - ``String.endsWith()`` + - ``String.slice()`` + - ``String.toUpperCase()`` + + * - ``String.indexOf()`` + - ``String.split()`` + - ``String.trim()`` + + * - ``String.lastIndexOf()`` + - ``String.startsWith()`` + - ``String.trimLeft()`` + + * - ``String.localeCompare()`` + - ``String.substr()`` + - ``String.trimRight()`` + + * - ``String.match()`` + - ``String.substring()`` + - + +.. _array-generics: + +Array Generic Methods +^^^^^^^^^^^^^^^^^^^^^ + +V8 does not support `Array generic methods +`_. +Array generics are a set of methods on the ``Array`` class that mirror +instance methods. + +.. example:: + + The following use of the generic method ``Array.every()`` is + **invalid** with V8: + + .. code-block:: javascript + + var arr = [4, 8, 15, 16, 23, 42]; + + function isEven (val) { + return 0 === val % 2; + } + + var allEven = Array.every(arr, isEven); + print(allEven); + + With V8, use the ``Array`` instance method ``every()`` available through + an *instance* of the ``Array`` class instead: + + .. code-block:: javascript + + var allEven = arr.every(isEven); + print(allEven); + +With V8, use the ``Array`` *instance* methods instead of the following +*generic* methods: + +.. list-table:: + + * - ``Array.concat()`` + - ``Array.lastIndexOf()`` + - ``Array.slice()`` + + * - ``Array.every()`` + - ``Array.map()`` + - ``Array.some()`` + + * - ``Array.filter()`` + - ``Array.pop()`` + - ``Array.sort()`` + + * - ``Array.forEach()`` + - ``Array.push()`` + - ``Array.splice()`` + + * - ``Array.indexOf()`` + - ``Array.reverse()`` + - ``Array.unshift()`` + + * - ``Array.join()`` + - ``Array.shift()`` + - + +Array Instance Method ``toSource()`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +V8 does not support the ``Array`` instance method `toSource() +`_. +Use the ``Array`` instance method ``toString()`` instead. + +``uneval()`` +^^^^^^^^^^^^ + +V8 does not support the non-standard method ``uneval()``. Use the +standardized `JSON.stringify() +`_ +method instead. + +Added Limitations for ``Map-Reduce`` and ``$where`` Operations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In MongoDB 2.4, :doc:`map-reduce operations +`, the :command:`group` command, and +:operator:`$where` operator expressions **cannot** access certain +global functions or properties, such as ``db``, that are available in +the :program:`mongo` shell. + +When upgrading to MongoDB 2.4, you will need to refactor your code if +your :doc:`map-reduce operations `, +:command:`group` commands, or :operator:`$where` operator expressions +include any global shell functions or properties that are no longer +available, such as ``db``. + +The following shell functions and properties **are available** to +:doc:`map-reduce operations `, the +:command:`group` command, and :operator:`$where` operator expressions +in MongoDB 2.4: + +.. list-table:: + :header-rows: 1 + + * - Available Properties + - Available Functions + - + + * - + | ``args`` + | ``MaxKey`` + | ``MinKey`` + + - + | ``assert()`` + | ``BinData()`` + | ``DBPointer()`` + | ``DBRef()`` + | ``doassert()`` + | ``emit()`` + | ``gc()`` + | ``HexData()`` + | ``hex_md5()`` + | ``isNumber()`` + | ``isObject()`` + | ``ISODate()`` + | ``isString()`` + + - + | ``Map()`` + | ``MD5()`` + | ``NumberInt()`` + | ``NumberLong()`` + | ``ObjectId()`` + | ``print()`` + | ``sleep()`` + | ``Timestamp()`` + | ``tojson()`` + | ``tojsononeline()`` + | ``tojsonObject()`` + | ``UUID()`` + | ``version()`` + +.. DOCS-752 + +New Geospatial Indexes with GeoJSON and Improved Spherical Geometry +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +MongoDB adds the new ``2dsphere`` geospatial index in addition to the +existing ``2d`` index. The ``2dsphere`` index supports improved +spherical queries and supports the following `GeoJSON +`_ objects: + +- ``Point`` + +- ``LineString`` + +- ``Polygon`` + +The ``2dsphere`` index supports all current geospatial :ref:`query +operators ` and introduces the following new +query operator for queries on GeoJSON data: + +- :operator:`$geoWithin` operator - This query will select all indexed objects that intersect with the - ``Point`` with the coordinates ``[ 40, 5 ]``. MongoDB will return - documents as intersecting if they have a shared edge. +- :operator:`$geoIntersects` operator - The :operator:`$geometry` operator takes a single `GeoJSON - document`_. +The operators use the new :operator:`$geometry` parameter. -.. operator:: $geometry +For more information, see: -.. _`GeoJSON document`: http://www.geojson.org/geojson-spec.html#appendix-a-geometry-examples +- :doc:`/applications/geospatial-indexes` -.. _`GeoJSON`: http://geojson.org/geojson-spec.html +- :doc:`/core/geospatial-indexes` New Hashed Index and Sharding with a Hashed Shard Key ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -759,92 +1279,6 @@ key. Consider the following properties when using a hashed shard key: point values, see :ref:`hashed indexes ` for more information. -Security Improvements -+++++++++++++++++++++ - -.. _kerberos-authentication: - -New Modular Authentication System with Support for Kerberos -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. note:: - - Kerberos authentication is only present in the `MongoDB Subscriber - Edition `_. - To download the 2.4.0 release candidate the Subscriber Edition, use - the following resources: - - - `Amazon Linux 6.4 `_ - - `Red Hat Enterprise Linux 6.2 `_ - - `Ubuntu 11.04 `_ - - `SUSE 11 `_ - -In 2.4 the MongoDB Subscriber edition now supports authentication via -a Kerberos mechanism. See -:doc:`/tutorial/control-access-to-mongodb-with-kerberos-authentication` -for more information. - -Also consider the following documents that address authenticating to -MongoDB using Kerberos: - -- :ecosystem:`Authenticate to MongoDB using Kerberos and the Java - Driver ` - -- :ecosystem:`Authenticate to MongoDB using Kerberos and the C# Driver - ` - -.. see:: :doc:`MongoDB Security Practices and Procedures `. - -Role Based Access Control and New Privilege Documents -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -MongoDB 2.4 introduces a role based access control system that -provides more granular privileges to MongoDB users. See -:doc:`/reference/user-privileges` for more information. - -To support the new access control system, 2.4 also introduces a new -format for documents in a database's :data:`system.user -<.system.user>` collection. See -:doc:`/reference/privilege-documents` for more information. - -Use :parameter:`supportCompatibilityFormPrivilegeDocuments` to disable -the legacy privilege documents, which MongoDB continues to support in -2.4. - -Administration Changes -++++++++++++++++++++++ - -``--setParameter`` Option Available on the ``mongos`` and ``mongod`` Command Line -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can now use :option:`--setParameter ` on the command line -and :setting:`setParameter` in the configuration file. Currently -:setting:`setParameter` provides the following options: - -.. include:: /includes/list-set-parameters.rst - -See :doc:`/reference/parameters` for full documentation of available -parameters and their use. - -Changes to ``serverStatus`` Output Including Additional Metrics -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In 2.4 MongoDB adds a number of counters and system metrics to the -output of the :dbcommand:`serverStatus` command, including: - -- a :ref:`working set estimator `. - -- operation counters, in :data:`~serverStatus.metrics.document` - and :data:`~serverStatus.metrics.operation`. - -- record allocation, in :data:`~serverStatus.metrics.record`. - -- thorough metrics of the replication process, - in :data:`~serverStatus.metrics.repl`. - -- metrics on the :doc:`ttl index ` - documentation. - Increased Chunk Migration Write Concern ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -867,18 +1301,6 @@ of sub-document nesting this validation may have a small performance impact. :setting:`objcheck`, which was previously disabled by default, provides this validation. -Indexing Changes -++++++++++++++++ - -Support for Multiple Concurrent Index Builds -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A single :program:`mongod` instance can build multiple indexes in the -background at the same time. See :ref:`building indexes in the -background ` for more information on -background index builds. Foreground index builds hold a database lock -and must proceed one at a time. - ``db.killOp()`` Can Now Kill Foreground Index Builds ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -886,9 +1308,6 @@ The :method:`db.killOp()` method will now terminate a foreground index build, in addition to the other operations supported in previous versions. -Interface Changes -+++++++++++++++++ - ``$setOnInsert`` -- New Update Operator ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -942,99 +1361,42 @@ modifiers: must be used with :operator:`$slice` and can **only** sort arrays that contain documents. -.. _rn-2.4-javascript-change: - -JavaScript Engine Changed to V8 -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -.. toctree:: - :hidden: - - /release-notes/2.4-javascript +``--setParameter`` Option Available on the ``mongos`` and ``mongod`` Command Line +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +You can now use :option:`--setParameter ` on the command line +and :setting:`setParameter` in the configuration file. Currently +:setting:`setParameter` provides the following options: -In 2.4 the default JavaScript engine in the :program:`mongo` shell -:program:`mongod` is now V8. This change affects all JavaScript -behavior including the :dbcommand:`mapReduce`, :dbcommand:`group`, and -:dbcommand:`eval` commands, as well as the :operator:`$where` query -operator. +.. include:: /includes/list-set-parameters.rst -Use the new :method:`interpreterVersion()` method in the -:program:`mongo` shell and the -:data:`~serverBuildInfo.interpreterVersion` field in the output of -:method:`db.serverBuildInfo()` to determine which JavaScript engine a -MongoDB binary uses. +See :doc:`/reference/parameters` for full documentation of available +parameters and their use. -The primary impacts of the change from the previous JavaScript engine, -SpiderMonkey, to V8 are: +Multiple Index Builds +~~~~~~~~~~~~~~~~~~~~~ -- improved concurancy for JavaScript operations, -- modernized JavaScript implementation, and -- removed non-standard SpiderMonkey features. - -See :doc:`/release-notes/2.4-javascript` for more information about -all changes . +A single :program:`mongod` instance can build multiple indexes in the +background at the same time. See :ref:`building indexes in the +background ` for more information on +background index builds. Foreground index builds hold a database lock +and must proceed one at a time. -Additional Limitations for Map-Reduce and ``$where`` Operations +Changes to ``serverStatus`` Output Including Additional Metrics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -In MongoDB 2.4, :doc:`map-reduce operations -`, the :command:`group` command, and -:operator:`$where` operator expressions **cannot** access certain -global functions or properties, such as ``db``, that are available in -the :program:`mongo` shell. - -When upgrading to MongoDB 2.4, you will need to refactor your code if -your :doc:`map-reduce operations `, -:command:`group` commands, or :operator:`$where` operator expressions -include any global shell functions or properties that are no longer -available, such as ``db``. - -The following shell functions and properties **are available** to -:doc:`map-reduce operations `, the -:command:`group` command, and :operator:`$where` operator expressions -in MongoDB 2.4: - -.. list-table:: - :header-rows: 1 +In 2.4 MongoDB adds a number of counters and system metrics to the +output of the :dbcommand:`serverStatus` command, including: - * - Available Properties - - Available Functions - - +- a :ref:`working set estimator `. - * - - | ``args`` - | ``MaxKey`` - | ``MinKey`` +- operation counters, in :data:`~serverStatus.metrics.document` + and :data:`~serverStatus.metrics.operation`. - - - | ``assert()`` - | ``BinData()`` - | ``DBPointer()`` - | ``DBRef()`` - | ``doassert()`` - | ``emit()`` - | ``gc()`` - | ``HexData()`` - | ``hex_md5()`` - | ``isNumber()`` - | ``isObject()`` - | ``ISODate()`` - | ``isString()`` +- record allocation, in :data:`~serverStatus.metrics.record`. - - - | ``Map()`` - | ``MD5()`` - | ``NumberInt()`` - | ``NumberLong()`` - | ``ObjectId()`` - | ``print()`` - | ``sleep()`` - | ``Timestamp()`` - | ``tojson()`` - | ``tojsononeline()`` - | ``tojsonObject()`` - | ``UUID()`` - | ``version()`` +- thorough metrics of the replication process, + in :data:`~serverStatus.metrics.repl`. -.. DOCS-752 +- metrics on the :doc:`ttl index ` + documentation. diff --git a/source/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes.txt b/source/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes.txt new file mode 100644 index 00000000000..b35c86019a8 --- /dev/null +++ b/source/tutorial/calculate-distances-using-spherical-geometry-with-2d-geospatial-indexes.txt @@ -0,0 +1,154 @@ +============================================================== +Calculate Distances in a ``2d`` Index Using Spherical Geometry +============================================================== + +.. default-domain:: mongodb + +.. note:: While basic queries using spherical distance are supported by + the ``2d`` index, consider moving to a ``2dsphere`` index if your + data is primarily longitude and latitude. + +The ``2d`` index supports queries that calculate distances on a +Euclidean plane (flat surface). The index also supports the following +query operators and command that calculate distances using spherical +geometry: + +- :operator:`$nearSphere` + +- :operator:`$centerSphere` + +- :operator:`$near` + +- :dbcommand:`geoNear` command with the ``{ spherical: true }`` option. + +.. important:: These three queries use radians for distance. Other query + types do not. + + For spherical query operators to function properly, you must convert + distances to radians, and convert from radians to the distances units + used by your application. + + To convert: + + - *distance to radians*: divide the distance by the radius of the + sphere (e.g. the Earth) in the same units as the distance + measurement. + + - *radians to distance*: multiply the radian measure by the radius + of the sphere (e.g. the Earth) in the units system that you want to + convert the distance to. + + The radius of the Earth is approximately ``3,959`` miles or + ``6,371`` kilometers. + +The following query would return documents from the ``places`` +collection within the circle described by the center ``[ -74, 40.74 ]`` +with a radius of ``100`` miles: + +.. code-block:: javascript + + db.places.find( { loc: { $geoWithin: { $centerSphere: [ [ -74, 40.74 ] , + 100 / 3959 ] } } } ) + +You may also use the ``distanceMultiplier`` option to the +:dbcommand:`geoNear` to convert radians in the :program:`mongod` +process, rather than in your application code. See :ref:`distance +multiplier `. + +The following spherical query, returns all documents in the +collection ``places`` within ``100`` miles from the point ``[ -74, +40.74 ]``. + +.. code-block:: javascript + + db.runCommand( { geoNear: "places", + near: [ -74, 40.74 ], + spherical: true + } ) + +The output of the above command would be: + +.. code-block:: javascript + + { + // [ ... ] + "results" : [ + { + "dis" : 0.01853688938212826, + "obj" : { + "_id" : ObjectId( ... ) + "loc" : [ + -73, + 40 + ] + } + } + ], + "stats" : { + // [ ... ] + "avgDistance" : 0.01853688938212826, + "maxDistance" : 0.01853714811400047 + }, + "ok" : 1 + } + +.. warning:: + + Spherical queries that wrap around the poles or at the transition + from ``-180`` to ``180`` longitude raise an error. + +.. note:: + + While the default Earth-like bounds for geospatial indexes are + between ``-180`` inclusive, and ``180``, valid values for latitude + are between ``-90`` and ``90``. + +.. _geospatial-indexes-distance-multiplier: + +Distance Multiplier +------------------- + +The ``distanceMultiplier`` option :dbcommand:`geoNear` returns distances +only after multiplying the results by an assigned value. This allows +MongoDB to return converted values, and removes the requirement to +convert units in application logic. + +Using ``distanceMultiplier`` in spherical queries provides results from +the :dbcommand:`geoNear` command that do not need radian-to-distance +conversion. The following example uses ``distanceMultiplier`` in the +:dbcommand:`geoNear` command with a :doc:`spherical +` example: + +.. code-block:: javascript + + db.runCommand( { geoNear: "places", + near: [ -74, 40.74 ], + spherical: true, + distanceMultiplier: 3959 + } ) + +The output of the above operation would resemble the following: + +.. code-block:: javascript + + { + // [ ... ] + "results" : [ + { + "dis" : 73.46525170413567, + "obj" : { + "_id" : ObjectId( ... ) + "loc" : [ + -73, + 40 + ] + } + } + ], + "stats" : { + // [ ... ] + "avgDistance" : 0.01853688938212826, + "maxDistance" : 0.01853714811400047 + }, + "ok" : 1 + }