Explain how to create and delete collections in MongoDB

  • 2020-05-30 21:14:56
  • OfStack

Create the collection: createCollection() method


MongoDB db.createCollection(name, options)
Is used to create collections.

Grammar:
The basic createCollection() command syntax is as follows:


db.createCollection(name, options)

In the command, name is the name of the collection to be created. Options is a file that specifies the configured collection
参数
类型
描述
Name String 要创建的集合名称
Options Document (可选)指定有关内存大小和索引选项

Option & # 8203; The & # 8203; The parameter is optional, so you only need to go to the specified collection name. Here is a list of options available:
字段
类型
描述
capped Boolean (可选)如果为true,则启用封顶集合。封顶集合是固定大小的集合,会自动覆盖最早的条目,当它达到其最大大小。如果指定true,则需要也指定尺寸参数。
autoIndexID Boolean (可选)如果为true,自动创建索引_id字段的默认值是false。
size number (可选)指定最大大小字节封顶集合。如果封顶如果是 true,那么你还需要指定这个字段。
max number (可选)指定封顶集合允许在文件的最大数量。

When a document is inserted, MongoDB 1 checks the size field to cap the top collection, and then it checks the largest field.

Example:
The basic syntax for the createCollection() method not to use options is as follows:


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

You can check by using the created collection command show collections

 >show collections mycollection system.indexes

The following example shows the syntax of the createCollection () method for several important options:

 >db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800, max : 10000 } ) { "ok" : 1 } >
In MongoDB, you do not need to create a collection. When inserting 1 some files MongoDB automatically creates the collection.

>db.yiibai.insert({"name" : "yiibai"}) >show collections mycol mycollection system.indexes yiibai >


Delete the collection: drop() method

The MongoDB


 db.collection.drop() 
Is used to delete a collection from the database.

Grammar:

The basic syntax of the drop() command is as follows


 db.COLLECTION_NAME.drop()

Example:

First, check the available collections in the database mydb


 >use mydb switched to db mydb >show collections mycol mycollection system.indexes yiibai >

Now remove the collection name as mycollection


 >db.mycollection.drop() true >

Check again the list of collections in the database

 >show collections mycol system.indexes yiibai >

The drop() method returns true, or false if the collection is successfully selected and discarded, otherwise

Related articles: