YouTip LogoYouTip

Mongodb Create Collection

MongoDB Create Collection

In this section, we will introduce how to use MongoDB to create a collection.

MongoDB uses the createCollection() method to create a collection.

Syntax:

db.createCollection(name, options)

Parameter Description:

  • name: The name of the collection to be created.
  • options: Optional parameters, specifying options related to memory size and indexes.

The options can be the following parameters:

Parameter Name Type Description Example Value
capped Boolean Whether to create a fixed-size collection. true
size Number Maximum size of the collection (in bytes). Only effective when capped is true. 10485760 (10MB)
max Number Maximum number of documents allowed in the collection. Only effective when capped is true. 5000
validator Object An expression for document validation. { $jsonSchema: { ... }}
validationLevel String Specifies the strictness of document validation. "off": No validation. "strict": Insert and update operations must pass validation (default). "moderate": Only existing documents must pass validation upon update; new documents do not need to. "strict"
validationAction String Specifies the action to take when document validation fails. "error": Prevents insertion or update (default). "warn": Allows insertion or update but issues a warning. "error"
storageEngine Object Specifies the storage engine configuration for the collection. { wiredTiger: { ... }}
collation Object Specifies the default collation for the collection. { locale: "en", strength: 2 }

When inserting documents, MongoDB first checks the size field of a capped collection, then checks the max field.

An example of creating a collection with these options:

Example

db.createCollection("myComplexCollection",{
    capped:true,
    size:10485760,
    max:5000,
    validator:{ $jsonSchema:{
        bsonType:"object",
        required:["name","email"],
        properties:{
            name:{
                bsonType:"string",
                description:"Must be a string and is required"
            },
            email:{
                bsonType:"string",
                pattern:"^.+@.+$",
                description:"Must be a valid email address"
            }
        }
    }},
    validationLevel:"strict",
    validationAction:"error",
    storageEngine:{
        wiredTiger:{ configString:"block_compressor=zstd"}
    },
    collation:{ locale:"en", strength:2}
});

This example creates a collection with the following characteristics:

  • Fixed size, maximum 10MB, storing up to 5000 documents.
  • Documents must contain name and email fields, where name must be a string and email must be in a valid email format.
  • Validation level is strict; failed validation will prevent insertion or update.
  • Uses the WiredTiger storage engine, specifying the block compressor as zstd.
  • Default uses English collation rules.

Example

Create a tutorial collection in the test database:

> use test
switched to db test
> db.createCollection("tutorial")
{ "ok" : 1 }
>

To view existing collections, you can use the show collections or show tables command:

> show collections
tutorial
system.indexes
>

Below is the usage of createCollection() with a few key parameters:

Creates a capped collection with a maximum size of 5MB (5242880 bytes) and a maximum of 5000 documents.

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

In MongoDB, you don't need to create a collection explicitly. When you insert some documents, MongoDB will automatically create the collection.

> db.mycol2.insert({"name" : ""})
> show collections
mycol2
...

Creates a capped collection with a maximum size of 1MB (1048576 bytes):

db.createCollection("myCappedCollection", { capped: true, size: 1048576 });

The following example creates a validator for the myCollection collection, requiring documents to have name and age fields, where name must be a string and age must be a non-negative integer.

Example

db.createCollection("myCollection",{
    validator:{ $jsonSchema:{
        bsonType:"object",
        required:["name","age"],
        properties:{
            name:{
                bsonType:"string",
                description:"Must be a string and is required"
            },
            age:{
                bsonType:"int",
                minimum:0,
                description:"Must be an integer and is required"
            }
        }
    }}
});
← Linux Comm TailVue Start β†’