collation.txt 9.98 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
=========
Collation
=========

.. default-domain:: mongodb

.. contents:: On this page
   :local:
   :backlinks: none
   :depth: 2
   :class: singlecol

.. versionadded:: 1.1

Overview
--------

MongoDB 3.4 introduced support for :manual:`collations
</manual/reference/collation/>`, which provide a set of rules to comply with the
conventions of a particular language when comparing strings.

For example, in Canadian French, the last accent in a given word determines the
sorting order. Consider the following French words:

.. code-block:: none

   cote < coté < côte < côté

The sort order using the Canadian French collation would result in the
following:

.. code-block:: none

   cote < côte < coté < côté

If collation is unspecified, MongoDB uses simple binary comparison for strings.
As such, the sort order of the words would be:

.. code-block:: none

    cote < coté < côte < côté

Usage
-----

You can specify a default collation for collections and indexes when they are
created, or specify a collation for CRUD operations and aggregations. For
operations that support collation, MongoDB uses the collection's default
collation unless the operation specifies a different collation.

Collation Parameters
~~~~~~~~~~~~~~~~~~~~

.. code-block:: php

   'collation' => [
       'locale' => <string>,
       'caseLevel' => <boolean>,
       'caseFirst' => <string>,
       'strength' => <integer>,
       'numericOrdering' => <boolean>,
       'alternate' => <string>,
       'maxVariable' => <string>,
       'normalization' => <boolean>,
       'backwards' => <boolean>,
   ]

The only required parameter is ``locale``, which the server parses as an `ICU
format locale ID <http://userguide.icu-project.org/locale>`_. For example, set
``locale`` to ``en_US`` to represent US English or ``fr_CA`` to represent
Canadian French.

For a complete description of the available parameters, see :manual:`Collation
Document </reference/collation/#collation-document>` in the MongoDB manual.

Assign a Default Collation to a Collection
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following example creates a new collection called ``contacts`` on the
``test`` database and assigns a default collation with the ``fr_CA`` locale.
Specifying a collation when you create the collection ensures that all
operations involving a query that are run against the ``contacts`` collection
use the ``fr_CA`` collation, unless the query specifies another collation. Any
indexes on the new collection also inherit the default collation, unless the
creation command specifies another collation.

.. code-block:: php

   <?php

   $database = (new MongoDB\Client)->test;

   $database->createCollection('contacts', [
       'collation' => ['locale' => 'fr_CA'],
   ]);

Assign a Collation to an Index
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To specify a collation for an index, use the ``collation`` option when you
create the index.

The following example creates an index on the ``name`` field of the
``address_book`` collection, with the ``unique`` parameter enabled and a default
collation with ``locale`` set to ``en_US``.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->address_book;

   $collection->createIndex(
       ['first_name' => 1],
       [
           'collation' => ['locale' => 'en_US'],
           'unique' => true,
       ]
   );

To use this index, make sure your queries also specify the same collation. The
following query uses the above index:

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->address_book;

   $cursor = $collection->find(
       ['first_name' => 'Adam'],
       [
           'collation' => ['locale' => 'en_US'],
       ]
   );

The following queries do **NOT** use the index. The first query uses no
collation, and the second uses a collation with a different ``strength`` value
than the collation on the index.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->address_book;

   $cursor1 = $collection->find(['first_name' => 'Adam']);

   $cursor2 = $collection->find(
       ['first_name' => 'Adam'],
       [
           'collation' => [
               'locale' => 'en_US',
               'strength' => 2,
           ],
       ]
   );

Operations that Support Collation
---------------------------------

All reading, updating, and deleting methods support collation. Some examples are
listed below.

``find()`` with ``sort``
~~~~~~~~~~~~~~~~~~~~~~~~

Individual queries can specify a collation to use when matching and sorting
results. The following query and sort operation uses a German collation with the
``locale`` parameter set to ``de``.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->contacts;

   $cursor = $collection->find(
       ['city' => 'New York'],
       [
           'collation' => ['locale' => 'de'],
           'sort' => ['name' => 1],
       ]
   );

``findOneAndUpdate()``
~~~~~~~~~~~~~~~~~~~~~~

A collection called ``names`` contains the following documents:

.. code-block:: javascript

   { "_id" : 1, "first_name" : "Hans" }
   { "_id" : 2, "first_name" : "Gunter" }
   { "_id" : 3, "first_name" : "Günter" }
   { "_id" : 4, "first_name" : "Jürgen" }

The following :phpmethod:`findOneAndUpdate()
<MongoDB\\Collection::findOneAndUpdate>` operation on the collection does not
specify a collation.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->names;

   $document = $collection->findOneAndUpdate(
       ['first_name' => ['$lt' =-> 'Gunter']],
       ['$set' => ['verified' => true]]
   );

Because ``Gunter`` is lexically first in the collection, the above operation
returns no results and updates no documents.

Consider the same :phpmethod:`findOneAndUpdate()
<MongoDB\\Collection::findOneAndUpdate>` operation but with a collation
specified, which uses the locale ``de@collation=phonebook``.

.. note::

   Some locales have a ``collation=phonebook`` option available for use with
   languages which sort proper nouns differently from other words. According to
   the ``de@collation=phonebook`` collation, characters with umlauts come before
   the same characters without umlauts.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->names;

   $document = $collection->findOneAndUpdate(
       ['first_name' => ['$lt' =-> 'Gunter']],
       ['$set' => ['verified' => true]],
       [
           'collation' => ['locale' => 'de@collation=phonebook'],
           'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER,
       ]
   );

The operation returns the following updated document:

.. code-block:: javascript

   { "_id" => 3, "first_name" => "Günter", "verified" => true }

``findOneAndDelete()``
~~~~~~~~~~~~~~~~~~~~~~

Set the ``numericOrdering`` collation parameter to ``true`` to compare numeric
strings by their numeric values.

The collection ``numbers`` contains the following documents:

.. code-block:: javascript

   { "_id" : 1, "a" : "16" }
   { "_id" : 2, "a" : "84" }
   { "_id" : 3, "a" : "179" }

The following example matches the first document in which field ``a`` has a
numeric value greater than 100 and deletes it.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->numbers;

   $document = $collection->findOneAndDelete(
       ['a' => ['$gt' =-> '100']],
       [
           'collation' => [
               'locale' => 'en',
               'numericOrdering' => true,
           ],
       ]
   );

After the above operation, the following documents remain in the collection:

.. code-block:: javascript

   { "_id" : 1, "a" : "16" }
   { "_id" : 2, "a" : "84" }

If you perform the same operation without collation, the server deletes the
first document it finds in which the lexical value of ``a`` is greater than
``"100"``.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->numbers;

   $document = $collection->findOneAndDelete(['a' => ['$gt' =-> '100']]);

After the above operation is executed, the document in which ``a`` was equal to
``"16"`` has been deleted, and the following documents remain in the collection:

.. code-block:: javascript

   { "_id" : 2, "a" : "84" }
   { "_id" : 3, "a" : "179" }

``deleteMany()``
~~~~~~~~~~~~~~~~

You can use collations with all the various CRUD operations which exist in the
|php-library|.

The collection ``recipes`` contains the following documents:

.. code-block:: javascript

   { "_id" : 1, "dish" : "veggie empanadas", "cuisine" : "Spanish" }
   { "_id" : 2, "dish" : "beef bourgignon", "cuisine" : "French" }
   { "_id" : 3, "dish" : "chicken molé", "cuisine" : "Mexican" }
   { "_id" : 4, "dish" : "chicken paillard", "cuisine" : "french" }
   { "_id" : 5, "dish" : "pozole verde", "cuisine" : "Mexican" }

Setting the ``strength`` parameter of the collation document to ``1`` or ``2``
causes the server to disregard case in the query filter. The following example
uses a case-insensitive query filter to delete all records in which the
``cuisine`` field matches ``French``.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->recipes;

   $collection->deleteMany(
       ['cuisine' => 'French'],
       [
           'collation' => [
               'locale' => 'en_US',
               'strength' => 1,
           ],
       ]
   );

After the above operation runs, the documents with ``_id`` values of ``2`` and
``4`` are deleted from the collection.

Aggregation
~~~~~~~~~~~

To use collation with an :phpmethod:`aggregate()
<MongoDB\\Collection::aggregate>` operation, specify a collation in the
aggregation options.

The following aggregation example uses a collection called ``names`` and groups
the ``first_name`` field together, counts the total number of results in each
group, and sorts the results by German phonebook order.

.. code-block:: php

   <?php

   $collection = (new MongoDB\Client)->test->recipes;

   $cursor = $collection->aggregate(
       [
           ['$group' => ['_id' => '$first_name', 'name_count' => ['$sum' => 1]]],
           ['$sort' => ['_id' => 1]],
       ],
       [
           'collation' => ['locale' => 'de@collation=phonebook'],
       ]
   );