WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

MongoDB - Create Collection


In this chapter, we show you how to use MongoDB to create collections.

The createCollection () method is used in MongoDB to create collections.

Syntax format:

db.createCollection(name, options)

Parameter description:

  • name: the name of the collection to create
  • options: optional parameters, specifying options regarding memory size and indexing

options can be the following parameters:

field Type Description
capped Boolean (Optional) If true, create a fixed collection. A fixed collection is a collection with a fixed size. When the maximum is reached, it will automatically overwrite the oldest document.
When the value is true, the size parameter must be specified.
autoIndexId Boolean (optional) If true, automatically create an index in the _id field. The default is false.
size Number (Optional) Specify a maximum value for the fixed collection, in kilobytes (KB).
If capped is true, you also need to specify this field.
max Number (Optional) Specifies the maximum number of documents in a fixed collection.

When inserting a document, MongoDB first checks the size field of the fixed collection, and then checks the max field.

Example

Create welookups collection in test database:

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

If you want to view existing collections, you can use show collections or show tables command´╝Ü

> show collections
welookups
system.indexes

Here is the usage of createCollection () with several key parameters:

Creating a fixed collection mycol, the size of the entire collection is 6142800 KB, and the maximum number of documents is 10,000.

> db.createCollection("mycol", { capped : true, autoIndexId : true, size : 
   6142800, max : 10000 } )
{ "ok" : 1 }
>

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

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




Welookups is optimized for learning. © 2018 -

All Right Reserved and you agree to have read and accepted our term and condition.