Cara menggunakan mongodb create collection

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

to create a:
  • New collection that uses document validation.

is a wrapper around the database command

The method has the following prototype form:

Note

Starting in MongoDB 4.2

MongoDB removes the MMAPv1 storage engine and the MMAPv1 specific options

changeStreamPreAndPostImages: {
enabled: <boolean>
}
4,
changeStreamPreAndPostImages: {
enabled: <boolean>
}
5,
changeStreamPreAndPostImages: {
enabled: <boolean>
}
6 for

db.createCollection( <name>,
{
capped: <boolean>,
timeseries: { // Added in MongoDB 5.0
timeField: <string>, // required for time series collections
metaField: <string>,
granularity: <string>
},
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>
}
)

The method has the following parameters:

Parameter

Type

Description

changeStreamPreAndPostImages: {
enabled: <boolean>
}
9

string

The name of the collection to create. See

{ <storage-engine-name>: <options> }
0

document

Optional. Configuration options for creating a:

  • Capped collection

  • Custered collection

  • View

The

{ <storage-engine-name>: <options> }
0 document contains the following fields:

Field

Type

Description

{ <storage-engine-name>: <options> }
2

boolean

Optional. To create a , specify

{ <storage-engine-name>: <options> }
3. If you specify
{ <storage-engine-name>: <options> }
3, you must also set a maximum size in the
{ <storage-engine-name>: <options> }
5 field.

{ <storage-engine-name>: <options> }
6

string

Required when creating a . 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

{ <storage-engine-name>: <options> }
7.

{ <storage-engine-name>: <options> }
8

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

{ <storage-engine-name>: <options> }
9 or the same as the
{ <storage-engine-name>: <options> }
6. The field can be of any type except array.

{ <storage-engine-name>: <options> }
1

string

Optional. Possible values are

{ <storage-engine-name>: <options> }
2 (default),
{ <storage-engine-name>: <options> }
3, and
{ <storage-engine-name>: <options> }
4. Set the granularity to the value that is the closest match to the time span between consecutive incoming measurements. Setting the
{ <storage-engine-name>: <options> }
5 parameter improves performance by optimizing how data in the time series collection is stored internally.

number

Optional. Specifies the seconds after which documents in a or expire. MongoDB deletes expired documents automatically.

For clustered collections, the documents are deleted automatically based on the clustered index key

{ <storage-engine-name>: <options> }
9 and the values must be date types. See

document

Starting in MongoDB 5.3, you can create a collection with a . Collections created with a clustered index are called clustered collections.

See

{ <storage-engine-name>: <options> }
7 has the following syntax:

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}

Field

Description

{ <storage-engine-name>: <options> }
8

Required. The clustered index key field. Must be set to

{ <storage-engine-name>: <options> }
9. The default value for the
{ <storage-engine-name>: <options> }
9 field is an automatically generated unique , but you can set your own

collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}
1

Required. Must be set to

{ <storage-engine-name>: <options> }
3. A unique index indicates the collection will not accept inserted or updated documents where the clustered index key value matches an existing value in the index.

changeStreamPreAndPostImages: {
enabled: <boolean>
}
9

Optional. A name that uniquely identifies the clustered index.

New in version 5.3.

document

Optional.

Starting in MongoDB 6.0, you can use to output the version of a document before and after changes (the document pre- and post-images):

  • The pre-image is the document before it was replaced, updated, or deleted. There is no pre-image for an inserted document.

  • The post-image is the document after it was inserted, replaced, or updated. There is no post-image for a deleted document.

  • Enable

    collation: {
    locale: <string>,
    caseLevel: <boolean>,
    caseFirst: <string>,
    strength: <int>,
    numericOrdering: <boolean>,
    alternate: <string>,
    maxVariable: <string>,
    backwards: <boolean>
    }
    4 for a collection using , , or

collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}
4 has the following syntax:

changeStreamPreAndPostImages: {
enabled: <boolean>
}

collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}
9

Description

{ <storage-engine-name>: <options> }
3

Enables change stream pre- and post-images for a collection.

db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )
1

Disables change stream pre- and post-images for a collection.

For complete examples with the change stream output, see

For a example on this page, see

New in version 6.0.

{ <storage-engine-name>: <options> }
5

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

{ <storage-engine-name>: <options> }
5 field is required for capped collections and ignored for other collections.

db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )
5

number

Optional. The maximum number of documents allowed in the capped collection. The

{ <storage-engine-name>: <options> }
5 limit takes precedence over this limit. If a capped collection reaches the
{ <storage-engine-name>: <options> }
5 limit before it reaches the maximum number of documents, MongoDB removes old documents. If you prefer to use the
db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )
5 limit, ensure that the
{ <storage-engine-name>: <options> }
5 limit, which is required for a capped collection, is sufficient to contain the maximum number of documents.

db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)
0

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

db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)
0 option should take the following form:

{ <storage-engine-name>: <options> }

Storage engine configuration specified when creating collections are validated and logged to the during replication to support replica sets with members that use different storage engines.

Tip

See also:

db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)
2

document

Optional. Allows users to specify validation rules or expressions for the collection. For more information, see Schema Validation.

The

db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)
2 option takes a document that specifies the validation rules or expressions. You can specify the expressions using the same operators as the with the exception of , , , and

To learn how to create a collection with schema validation, see

db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)
8

string

Optional. Determines how strictly MongoDB applies the validation rules to existing documents during an update.

db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)
8

Description

db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)
0

No validation for inserts or updates.

db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)
1

Default Apply validation rules to all inserts and all updates.

db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)
2

Apply validation rules to inserts and to updates on existing valid documents. Do not apply rules to updates on existing invalid documents.

To see an example that uses

db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)
8, see

db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)
4

string

Optional. Determines whether to

db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)
5 on invalid documents or just
db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)
6 about the violations but allow invalid documents to be inserted.

Important

Validation of documents only applies to those documents as determined by the

db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)
8.

To see an example that uses

db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)
4, see

db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)
9

document

Optional. Allows users to specify a default configuration for indexes when creating a collection.

The

db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)
9 option accepts a
db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)
0 document, which should take the following form:

{ <storage-engine-name>: <options> }

Storage engine configuration specified when creating indexes are validated and logged to the during replication to support replica sets with members that use different storage engines.

db.createCollection(
"temperatureSensor",
{ changeStreamPreAndPostImages: { enabled: true } }
);
2

string

The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view; i.e. does not include the database name and implies the same database as the view to create. You must create views in the same database as the source collection.

See also

db.createCollection(
"temperatureSensor",
{ changeStreamPreAndPostImages: { enabled: true } }
);
4

array

An array that consists of the . creates the view by applying the specified

db.createCollection(
"temperatureSensor",
{ changeStreamPreAndPostImages: { enabled: true } }
);
4 to the
db.createCollection(
"temperatureSensor",
{ changeStreamPreAndPostImages: { enabled: true } }
);
2 collection or view.

A view definition

db.createCollection(
"temperatureSensor",
{ changeStreamPreAndPostImages: { enabled: true } }
);
4 cannot include the or the stage. This restriction also applies to embedded pipelines, such as pipelines used in or stages.

The view definition is public; i.e. and

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
04 operations on the view will include the pipeline that defines the view. As such, avoid referring directly to sensitive fields and values in view definitions.

See also

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
06

document

Specifies the default for the collection.

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

The collation option has the following syntax:

collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}

When specifying collation, the

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
07 field is mandatory; all other collation fields are optional. For descriptions of the fields, see

If you specify a collation at the collection level:

  • Indexes on that collection will be created with that collation unless the index creation operation explicitly specify a different collation.

  • Operations on that collection use the collection's default collation unless they explicitly specify a different collation.

    You cannot specify multiple collations for an operation. For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.

If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.

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

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
08

document

Optional. A document that expresses the write concern for the operation. Omit to use the default write concern.

When issued on a sharded cluster, converts the write concern of the command and its helper to

Access Control

If the deployment enforces , requires the following privileges:

Task

Required Privileges

Create a non-capped collection

on the database, or

on the collection to create

Create a

for the collection

on the database

Create a

on the database.

However, if the user has the on the database and on the view to create, the user must also have the following additional permissions:

  • on the source collection or view.

  • on any other collections or views referenced in the

    db.createCollection(
    "temperatureSensor",
    { changeStreamPreAndPostImages: { enabled: true } }
    );
    4, if any.

A user with the built in role on the database has the required privileges to run the listed operations. Either create a user with the required role or

Behavior

Resource Locking

Changed in version 4.2.

obtains an exclusive lock on the specified collection or view for the duration of the operation. All subsequent operations on the collection must wait until releases the lock. typically holds this lock for a short time.

Creating a view requires obtaining an additional exclusive lock on the

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
28 collection in the database. This lock blocks creation or modification of views in the database until the command completes.

Transactions

Changed in version 4.4.

Starting in MongoDB 4.4, you can create collections and indexes inside a if the transaction is

not a cross-shard write transaction.

To use in a transaction, the transaction must use read concern . If you specify a read concern level other than , the transaction fails.

Tip

See also:

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:

db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )

This command creates a collection named

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
32 with a maximum size of 5 megabytes and a maximum of 5000 documents.

See Capped Collections for more information about capped collections.

Create a Time Series Collection

To create a that captures weather data for the past 24 hours, issue this command:

db.createCollection(
"weather24h",
{
timeseries: {
timeField: "timestamp",
metaField: "data",
granularity: "hours"
},
expireAfterSeconds: 86400
}
)

Create a Clustered Collection

The following example adds a named

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
34:

db.createCollection(
"stocks",
{ clusteredIndex: { "key": { _id: 1 }, "unique": true, "name": "stocks clustered key" } }
)

In the example, specifies:

  • clusteredIndex: {
    key: { <string> },
    unique: <boolean>,
    name: <string>
    }
    35, which sets the clustered index key to the
    { <storage-engine-name>: <options> }
    9 field.

  • clusteredIndex: {
    key: { <string> },
    unique: <boolean>,
    name: <string>
    }
    37, which indicates the clustered index key value must be unique.

  • clusteredIndex: {
    key: { <string> },
    unique: <boolean>,
    name: <string>
    }
    38, which sets the clustered index name.

Create a Collection with Change Stream Pre- and Post-Images for Documents

Starting in MongoDB 6.0, you can use to output the version of a document before and after changes (the document pre- and post-images):

  • The pre-image is the document before it was replaced, updated, or deleted. There is no pre-image for an inserted document.

  • The post-image is the document after it was inserted, replaced, or updated. There is no post-image for a deleted document.

  • Enable

    collation: {
    locale: <string>,
    caseLevel: <boolean>,
    caseFirst: <string>,
    strength: <int>,
    numericOrdering: <boolean>,
    alternate: <string>,
    maxVariable: <string>,
    backwards: <boolean>
    }
    4 for a collection using , , or

The following example creates a collection that has enabled:

db.createCollection(
"temperatureSensor",
{ changeStreamPreAndPostImages: { enabled: true } }
);

Pre- and post-images are not available for a if the images were:

  • Not enabled on the collection at the time of a document update or delete operation.

  • Removed after the pre- and post-image retention time set in

    clusteredIndex: {
    key: { <string> },
    unique: <boolean>,
    name: <string>
    }
    43.

    • The following example sets

      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      43 to
      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      45 seconds:

      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      0

    • The following example returns the current

      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      46 settings, including
      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      43:

      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      1

    • Setting

      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      43 to
      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      49 uses the default retention policy: pre- and post-images are retained until the corresponding change stream events are removed from the

    • If a change stream event is removed from the oplog, then the corresponding pre- and post-images are also deleted regardless of the

      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      43 pre- and post-image retention time.

Additional considerations:

  • Enabling pre- and post-images consumes storage space and adds processing time. Only enable pre- and post-images if you need them.

  • Limit the change stream event size to less than 16 megabytes. To limit the event size, you can:

    • Limit the document size to 8 megabytes. You can request pre- and post-images simultaneously in the if other change stream event fields like

      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      51 are not large.

    • Request only post-images in the change stream output for documents up to 16 megabytes if other change stream event fields like

      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      51 are not large.

    • Request only pre-images in the change stream output for documents up to 16 megabytes if:

      • document updates affect only a small fraction of the document structure or content, and

      • do not cause a

        clusteredIndex: {
        key: { <string> },
        unique: <boolean>,
        name: <string>
        }
        53 change event. A
        clusteredIndex: {
        key: { <string> },
        unique: <boolean>,
        name: <string>
        }
        53 event always includes the post-image.

  • To request a pre-image, you set

    clusteredIndex: {
    key: { <string> },
    unique: <boolean>,
    name: <string>
    }
    55 to
    clusteredIndex: {
    key: { <string> },
    unique: <boolean>,
    name: <string>
    }
    56 or
    clusteredIndex: {
    key: { <string> },
    unique: <boolean>,
    name: <string>
    }
    57 in . To request a post-image, you set
    clusteredIndex: {
    key: { <string> },
    unique: <boolean>,
    name: <string>
    }
    59 using the same method.

  • Pre-images are written to the

    clusteredIndex: {
    key: { <string> },
    unique: <boolean>,
    name: <string>
    }
    60 collection.

    • The

      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      60 collection may become large. To limit the collection size, you can set
      clusteredIndex: {
      key: { <string> },
      unique: <boolean>,
      name: <string>
      }
      43 time for the pre-images as shown earlier.

    • Pre-images are removed asynchronously by a background process.

Important

Backward-Incompatible Feature

Starting in MongoDB 6.0, if you are using document pre- and post-images for , you must disable for each collection using the command before you can downgrade to an earlier MongoDB version.

Tip

See also:

  • For change stream events and output, see

  • To watch a collection for changes, see

  • For complete examples with the change stream output, see

Specify Collation

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

You can specify at the collection or level. For example, the following operation creates a collection, specifying a collation for the collection (See for descriptions of the collation fields):

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
2

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

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
65:

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
3

The following operation uses the collection's collation:

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
4

The operation returns documents in the following order:

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
5

The same operation on a collection that uses simple binary collation (i.e. no specific collation set) returns documents in the following order:

clusteredIndex: {
key: { <string> },
unique: <boolean>,
name: <string>
}
6

Tip

See also:

Specify Storage Engine Options

You can specify collection-specific storage engine configuration options when you create a collection with . Consider the following operation:

Apa itu Collection dalam MongoDB?

Collection MongoDb adalah tempat kumpulan informasi data yang berbentuk dokumen. Collection dipadankan seperti tabel-tabel yang berisi data pada database SQL. Document MongoDb adalah satuan unit terkecil dalam MongoDB.

Kapan harus menggunakan MongoDB?

Kapan Menggunakan MongoDB Misalnya kamu memiliki toko online yang ramai pelanggan yang setiap menitnya terdapat ada 100 data pelanggan yang masuk. Selain itu kamu juga bisa menggunakan MongoDB saat data yang didapatkan berkembang secara cepat dan memiliki struktur data yang kompleks.

Apakah MongoDB free?

MongoDB adalah software sistem database yang bisa Anda gunakan gratis, baik untuk pengguna Windows, Linux atau macOS. Ini tentu pilihan yang cocok apabila Anda sedang mengerjakan project kecil atau pribadi dan tidak menyediakan anggaran khusus untuk membeli lisensi.

Mengapa MongoDB disebut database berorientasi dokumen?

Berorientasi pada dokumen-Karena MongoDB adalah database tipe NoSQL, alih-alih memiliki data dalam format tipe relasional, MongoDB menyimpan data dalam dokumen. Ini membuat MongoDB sangat fleksibel dan mudah beradaptasi dengan situasi dan persyaratan dunia bisnis nyata.