MongoDB Basic Primer for creating and deleting collections
- 2020-11-26 19:02:32
- OfStack
Create a collection
Syntax format
db.createCollection(name, {capped: <Boolean>, autoIndexId: <Boolean>, size: <number>, max <number>})
Parameters that
name: Name of the collection to be created options: Optional parameter that specifies options for memory size and indexesoptions parameter description
参数名 | 参数类型 | 参数说明 |
---|---|---|
capped | 布尔 | 如果为 true,则创建固定集合。默认为不启用<br />固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。<br />当该值为 true 时,必须指定 size 参数。 |
autoIndexId | 布尔 | 如为 true,自动在 _id 字段创建索引。默认为 false |
size | 数值 | 为固定集合指定1个最大值 默认为没有限制。 如果 capped 为 true,也需要指定该字段。 |
max | 数值 | 指定固定集合中包含文档的最大数量。 |
_id:mongodb automatically generates _id as the primary key when the document is created, but it is not autogenous
When a fixed collection is inserted into a document, MongoDB first checks the size field of the fixed collection, and then checks the max field.
Examples of usage
A fixed collection, myCollection, was created. The size of the entire collection space was 1024,000 KB, and the maximum number of documents was 10,000.
> use test
switched to db test
> db.createCollection("myCollection", {capped : true, autoIndexId : true, size : 1024000, max : 10000})
{
"note" : "the autoIndexId option is deprecated and will be removed in a future release",
"ok" : 1
}
> show collections
myCollection
[
"note" : "the autoIndexId is deprecated will be removed in future release". The _id index is not officially approved and will be removed in future releases
]
In fact, in MongoDB, you don't need to create a collection. MongoDB automatically creates collections when you insert 1 document.
> show collections
myCollection
> db.myCollection2.insert({"name":" Love is you ", "age":27})
WriteResult({ "nInserted" : 1 })
> show collections
myCollection
myCollection2
>
Delete the collection
Syntax format
db.collectionName.drop()
[
collectionName is replaced with the collection name
]
The return value
The drop() method returns true if the selected collection was successfully deleted, or false if not.
The instance
> show collections
myCollection
myCollection2
> db.myCollection2.drop()
true
> show collections
myCollection
conclusion