-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathdb.createCollection.txt
572 lines (399 loc) · 17.4 KB
/
db.createCollection.txt
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
=====================
db.createCollection()
=====================
.. default-domain:: mongodb
.. meta::
:description: Create a new collection.
.. facet::
:name: programming_language
:values: shell
.. contents:: On this page
:local:
:backlinks: none
:depth: 1
:class: singlecol
Definition
----------
.. method:: db.createCollection(name, options)
Creates a new collection. For :ref:`views <views-landing-page>`,
see :method:`db.createView()`.
Because MongoDB creates a collection implicitly when the collection
is first referenced in a command, this method is used primarily for
creating new collections that use specific options. For example, you
use ``db.createCollection()`` to create a:
- :term:`Capped collection <capped collection>`.
- :term:`Clustered collection <clustered collection>`.
- New collection that uses :ref:`schema validation
<schema-validation-overview>`.
``db.createCollection()`` is a wrapper around the database
command :dbcommand:`create`.
Compatibility
-------------
This method is available in deployments hosted in the following environments:
.. include:: /includes/fact-environments-atlas-only.rst
.. include:: /includes/fact-environments-atlas-support-all.rst
.. include:: /includes/fact-environments-onprem-only.rst
.. _db-create-collection-syntax:
Syntax
------
The ``db.createCollection()`` method has the following
prototype form:
.. code-block:: javascript
db.createCollection( <name>,
{
capped: <boolean>,
timeseries: { // Added in MongoDB 5.0
timeField: <string>, // required for time series collections
metaField: <string>,
granularity: <string>,
bucketMaxSpanSeconds: <number>, // Added in MongoDB 6.3
bucketRoundingSeconds: <number> // Added in MongoDB 6.3
},
expireAfterSeconds: <number>,
clusteredIndex: <document>, // Added in MongoDB 5.3
changeStreamPreAndPostImages: <document>, // Added in MongoDB 6.0
size: <number>,
max: <number>,
storageEngine: <document>,
validator: <document>,
validationLevel: <string>,
validationAction: <string>,
indexOptionDefaults: <document>,
viewOn: <string>,
pipeline: <pipeline>,
collation: <document>,
writeConcern: <document>
}
)
.. _create_collection_parameters:
The ``db.createCollection()`` method has the following parameters:
.. list-table::
:header-rows: 1
:widths: 20 20 80
* - Parameter
- Type
- Description
* - ``name``
- string
- The name of the collection to create. See
:ref:`restrictions-on-db-names`.
* - ``options``
- document
- Optional. Configuration options for creating a:
- Capped collection
- Clustered collection
- View
The ``options`` document contains the following fields:
.. list-table::
:header-rows: 1
:widths: 25 20 75
* - Field
- Type
- Description
* - ``capped``
- boolean
- Optional. To create a :term:`capped collection`,
specify ``true``. If you specify ``true``, you must also set a
maximum size in the ``size`` field.
* - ``timeseries.timeField``
- string
- Required when creating a :term:`time series collection`. The
name of the field which contains the date in each time series
document. Documents in a time series collection must have a
valid BSON date as the value for the ``timeField``.
* - ``timeseries.metaField``
- string
- Optional. The name of the field which contains metadata in
each time series document. The metadata in the specified field
should be data that is used to label a unique series of
documents. The metadata should rarely, if ever, change.
The name of the specified field may not be ``_id`` or the same
as the ``timeseries.timeField``. The field can be of any type
except array.
* - ``timeseries.granularity``
- string
- Optional, do not use if setting ``bucketRoundingSeconds`` and
``bucketMaxSpanSeconds``. Possible values are ``seconds``
(default), ``minutes``, and ``hours``.
Set ``granularity`` to the value that most closely matches
the time between consecutive incoming timestamps. This
improves performance by optimizing how MongoDB internally
stores data in the collection.
For more information on granularity and bucket intervals, see
:ref:`timeseries-granularity`.
* - ``timeseries.bucketMaxSpanSeconds``
- integer
- Optional, used with ``bucketRoundingSeconds`` as an
alternative to ``granularity``. Sets the maximum time between
timestamps in the same bucket. Possible values are 1-31536000.
If you set ``bucketMaxSpanSeconds``, you must set
``bucketRoundingSeconds`` to the same value.
To downgrade below MongoDB 6.3, you must either modify the
collection to use the corresponding ``granularity`` value, or
drop the collection. For details, see :dbcommand:`collMod`.
* - ``timeseries.bucketRoundingSeconds``
- integer
- Optional, used with ``bucketMaxSpanSeconds`` as an alternative
to ``granularity``. Sets the number of seconds to round down
by when MongoDB sets the minimum timestamp for a new bucket.
Must be equal to ``bucketMaxSpanSeconds``.
For example, setting both parameters to ``1800`` rounds new
buckets down to the nearest 30 minutes. If a document with a
time of ``2023-03-27T18:24:35Z`` does not fit an
existing bucket, MongoDB creates a new bucket with a minimum
time of ``2023-03-27T18:00:00Z`` and a maximum time of
``2023-03-27T18:30:00Z``.
* - ``expireAfterSeconds``
- number
- .. _db.createCollection.expireAfterSeconds:
Optional. Specifies the seconds after which documents in a
:term:`time series collection` or :term:`clustered collection`
expire. MongoDB deletes expired documents automatically.
For clustered collections, the documents are deleted
automatically based on the clustered index key ``_id`` and
the values must be date types. See :ref:`index-feature-ttl`.
* - ``clusteredIndex``
- document
- .. _db.createCollection.clusteredIndex:
.. include:: /includes/clustered-index-fields.rst
* - ``changeStreamPreAndPostImages``
- document
- .. _db.createCollection.changeStreamPreAndPostImages:
.. include:: /includes/change-stream-pre-and-post-images-field.rst
For a ``db.createCollection()`` example on this page,
see
:ref:`createCollection-change-stream-pre-and-post-images-example`.
.. versionadded:: 6.0
* - ``size``
- number
- Optional. Specify a maximum size in bytes for a capped
collection. Once a capped collection reaches its maximum size,
MongoDB removes the older documents to make space for the new
documents. The ``size`` field is required for capped collections
and ignored for other collections.
* - ``max``
- number
- Optional. The maximum number of documents allowed in the capped
collection. The ``size`` limit takes precedence over this limit.
If a capped collection reaches the ``size`` limit before it
reaches the maximum number of documents, MongoDB removes old
documents. If you prefer to use the ``max`` limit, ensure that
the ``size`` limit, which is required for a capped collection,
is sufficient to contain the maximum number of documents.
* - ``storageEngine``
- document
- Optional. Available for the WiredTiger storage engine only.
Allows users to specify configuration to the storage engine on a
per-collection basis when creating a collection. The value of the
``storageEngine`` option should take the following form:
.. code-block:: javascript
{ <storage-engine-name>: <options> }
Storage engine configuration specified when creating collections
are validated and logged to the :term:`oplog` during replication
to support replica sets with members that use different storage
engines.
.. include:: /includes/fact-encryption-options-create-collection.rst
For details, see :ref:`create-collection-storage-engine-options`.
* - ``validator``
- document
- Optional. Allows users to specify :ref:`validation rules or
expressions <schema-validation-overview>` for the collection.
The ``validator`` option takes a document that specifies the
validation rules or expressions. You can specify the expressions
using the same operators as the :ref:`query operators
<query-selectors>` with the exception of :query:`$near`,
:query:`$nearSphere`, :query:`$text`, and :query:`$where`.
To learn how to create a collection with schema validation,
see :ref:`schema-validation-json`.
* - ``validationLevel``
- string
- Optional. Determines how strictly MongoDB applies the
validation rules to existing documents during an update.
.. include:: /includes/extracts/table-validationLevel-values.rst
To see an example that uses ``validationLevel``, see
:ref:`schema-specify-validation-level`.
* - ``validationAction``
- string
- Optional. Determines whether to ``error`` on invalid documents
or just ``warn`` about the violations but allow invalid
documents to be inserted.
:gold:`IMPORTANT:` Validation of documents only applies to those
documents as determined by the ``validationLevel``.
To see an example that uses ``validationAction``, see
:ref:`schema-validation-handle-invalid-docs`.
* - ``indexOptionDefaults``
- document
- Optional. Allows users to specify a default configuration for
indexes when creating a collection.
The ``indexOptionDefaults`` option accepts a ``storageEngine``
document, which should take the following form:
.. code-block:: javascript
{ <storage-engine-name>: <options> }
Storage engine configuration specified when creating indexes are
validated and logged to the :term:`oplog` during replication to
support replica sets with members that use different storage
engines.
* - ``viewOn``
- string
- The name of the source collection or view from which to create
a view. For details, see :method:`db.createView()`.
* - ``pipeline``
- array
- An array that consists of the :ref:`aggregation pipeline stage(s)
<aggregation-pipeline>`. :method:`db.createView` creates a
view by applying the specified ``pipeline`` to the ``viewOn``
collection or view. For details, see :method:`db.createView()`.
* - ``collation``
- document
- Specifies the default :ref:`collation <collation>` for the
collection.
.. include:: /includes/extracts/collation-description.rst
.. include:: /includes/extracts/collation-option-specification.rst
.. include:: /includes/extracts/collation-collection-level.rst
.. include:: /includes/extracts/collation-unspecified.rst
For a collection, you can only specify the collation during the
collection creation. Once set, you cannot modify the collection's
default collation.
For an example, see :ref:`createCollection-collation-example`.
* - ``writeConcern``
- document
- Optional. A document that expresses the :ref:`write concern
<write-concern>` for the operation. Omit to use the default write
concern.
.. include:: /includes/extracts/mongos-operations-wc-create.rst
Access Control
--------------
.. include:: /includes/extracts/access-control-createCollection.rst
Behavior
--------
``db.createCollection()`` has the following behavior:
Resource Locking
~~~~~~~~~~~~~~~~
.. include:: /includes/extracts/createCollection-resource-lock.rst
Transactions
~~~~~~~~~~~~
.. include:: /includes/extracts/transactions-explicit-ddl.rst
.. |operation| replace:: ``db.createCollection()``
Collection or View with Same Name and Options
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /includes/createCollection-idempotence.rst
Examples
--------
Create a Capped Collection
~~~~~~~~~~~~~~~~~~~~~~~~~~
Capped collections
have maximum size or document counts that prevent them from growing
beyond maximum thresholds. All capped collections must specify a maximum
size and may also specify a maximum document count. MongoDB removes
older documents if a collection reaches the maximum size limit before it
reaches the maximum document count. Consider the following example:
.. code-block:: javascript
db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )
This command creates a collection named ``log`` with a maximum size of 5
megabytes and a maximum of 5000 documents.
See :ref:`manual-capped-collection` for more
information about capped collections.
Create a Time Series Collection
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To create a :term:`time series collection` that captures weather data
for the past 24 hours, issue this command:
.. code-block:: javascript
db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)
Alternately, to create the same collection but limit each bucket to
timestamp values within the same hour, issue this command:
.. code-block:: javascript
db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
bucketMaxSpanSeconds: "3600",
bucketRoundingSeconds: "3600"
},
expireAfterSeconds: 86400
}
)
Create a Clustered Collection
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /includes/db-create-clustered-collection-example.rst
.. _createCollection-change-stream-pre-and-post-images-example:
Create a Collection with Change Stream Pre- and Post-Images for Documents
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. include:: /includes/change-stream-pre-and-post-images-introduction.rst
The following example creates a collection that has
:ref:`changeStreamPreAndPostImages
<db.createCollection.changeStreamPreAndPostImages>` enabled:
.. code-block:: javascript
db.createCollection(
"temperatureSensor",
{ changeStreamPreAndPostImages: { enabled: true } }
);
.. include:: /includes/change-stream-pre-and-post-images-additional-information.rst
.. _createCollection-collation-example:
Specify Collation
~~~~~~~~~~~~~~~~~
.. include:: /includes/extracts/collation-versionadded.rst
You can specify :ref:`collation <collation>` at the collection or
:ref:`view <views-landing-page>` level. For example, the following
operation creates a collection, specifying a collation for the
collection (See :ref:`collation-document-fields` for descriptions of
the collation fields):
.. code-block:: javascript
db.createCollection( "myColl", { collation: { locale: "fr" } } );
This collation will be used by indexes and operations that support
collation unless they explicitly specify a different collation. For
example, insert the following documents into ``myColl``:
.. code-block:: javascript
{ _id: 1, category: "café" }
{ _id: 2, category: "cafe" }
{ _id: 3, category: "cafE" }
The following operation uses the collection's collation:
.. code-block:: javascript
db.myColl.find().sort( { category: 1 } )
The operation returns documents in the following order:
.. code-block:: javascript
{ "_id" : 2, "category" : "cafe" }
{ "_id" : 3, "category" : "cafE" }
{ "_id" : 1, "category" : "café" }
The same operation on a collection that uses simple binary collation
(i.e. no specific collation set) returns documents in the following order:
.. code-block:: javascript
{ "_id" : 3, "category" : "cafE" }
{ "_id" : 2, "category" : "cafe" }
{ "_id" : 1, "category" : "café" }
.. seealso::
:ref:`create-view-w-collation`
.. _create-collection-storage-engine-options:
Specify Storage Engine Options
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can specify collection-specific storage engine configuration
options when you create a collection with
``db.createCollection()``. Consider the following operation:
.. code-block:: javascript
db.createCollection(
"users",
{ storageEngine: { wiredTiger: { configString: "<option>=<setting>" } } }
)
This operation creates a new collection named ``users`` with a
specific configuration string that MongoDB will pass to the
``wiredTiger`` storage engine.
For example, to specify the ``zlib`` compressor for file blocks in the
``users`` collection, set the ``block_compressor`` option with the
following command:
.. code-block:: javascript
db.createCollection(
"users",
{ storageEngine: { wiredTiger: { configString: "block_compressor=zlib" } } }
)
.. include:: /includes/fact-encryption-options-create-collection.rst