MongoDB create a collection
In this section we show you how to use MongoDB to create collections.
MongoDB uses the createCollection() method to create collections.
Syntax format:
db.createCollection(name, options)
Copy the code
Parameter Description:
- Name: Name of the collection to be created
- Options: Optional parameters that specify memory size and index options
Options can be the following parameters:
field | type | describe |
---|---|---|
capped | Boolean | (Optional) If true, a fixed collection is created. A fixed collection is a collection of a fixed size that automatically overwrites the earliest documents when it reaches its maximum.When this value is true, the size argument must be specified. |
autoIndexId | Boolean | (Optional) If the value is true, the index is automatically created in the _ID field. The default is false. |
size | The numerical | (Optional) Specify a maximum value (in bytes) for the fixed collection.This field also needs to be specified if capped is true. |
max | The numerical | (Optional) Specifies the maximum number of documents to contain in a fixed collection. |
When inserting a document, MongoDB checks the size field of the fixed collection first, and then the Max field.
The instance
Create runoob collection in test database:
> use test
switched to db test
> db.createCollection("runoob")
{ "ok" : 1 }
>
Copy the code
To view existing collections, use the show collections command:
> show collections
runoob
system.indexes
Copy the code
Here’s how to use createCollection() with a few key arguments:
Create a fixed collection mycol, the size of the entire collection 6142800 KB, the maximum number of documents is 10000.
> db.createCollection("mycol", { capped : true, autoIndexId : true, size :
6142800, max : 10000 } )
{ "ok" : 1 }
>
Copy the code
In MongoDB, you don’t need to create collections. When you insert documents, MongoDB automatically creates collections.
> db.mycol2.insert({"name" : "test "}) > show collections mycol2...Copy the code
MongoDB delete collection
In this section we show you how to use MongoDB to delete collections.
MongoDB uses the drop() method to drop collections.
Syntax format:
db.collection.drop()
Copy the code
Parameter Description:
- There is no
The return value
The drop() method returns true if the selected collection was successfully dropped, false otherwise.
The instance
In myDB, we can first look at existing collections using the show Collections command:
>use mydb
switched to db mydb
>show collections
mycol
mycol2
system.indexes
runoob
>
Copy the code
Then delete the collection mycol2:
>db.mycol2.drop()
true
>
Copy the code
Show Collections to see collections in database myDB again:
>show collections
mycol
system.indexes
runoob
>
Copy the code
You can see from the results that the myCOL2 collection has been deleted.