MongoDB的集合操作

作者: 缘来是你ylh | 来源:发表于2019-03-02 01:48 被阅读6次

    创建集合

    语法格式

    db.createCollection(name, {capped: <Boolean>, autoIndexId: <Boolean>, size: <number>, max <number>})
    

    参数说明

    • name: 要创建的集合的名称
    • options: 可选参数,指定有关内存大小及索引的选项

    options参数说明

    参数名 参数类型 参数说明
    capped 布尔 如果为 true,则创建固定集合。默认为不启用<br />固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。<br />当该值为 true 时,必须指定 size 参数。
    autoIndexId 布尔 如为 true,自动在 _id 字段创建索引。默认为 false
    size 数值 为固定集合指定一个最大值 默认为没有限制。
    如果 capped 为 true,也需要指定该字段。
    max 数值 指定固定集合中包含文档的最大数量。

    _id:mongodb在创建文档的时候会自动生成_id作为主键,但不是自增的

    在固定集合在插入文档时,MongoDB 首先检查固定集合的 size 字段,然后检查 max 字段。

    用法实例

    创建固定集合 myCollection,整个集合空间大小 1024000 KB, 文档最大个数为 10000个。

    > 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 option is deprecated and will be removed in a future release"。官方不赞成给_id创建索引,以后发布的版本会将这个移除

    其实,在 MongoDB 中,你不需要创建集合。当你插入一些文档时,MongoDB 会自动创建集合。

    > show collections
    myCollection
    > db.myCollection2.insert({"name":"缘来是你", "age":27})
    WriteResult({ "nInserted" : 1 })
    > show collections
    myCollection
    myCollection2
    >
    

    删除集合

    语法格式

    db.collectionName.drop()
    

    collectionName替换为集合名称

    返回值

    如果成功删除选定集合,则 drop() 方法返回 true,否则返回 false。

    实例

    > show collections
    myCollection
    myCollection2
    > db.myCollection2.drop()
    true
    > show collections
    myCollection
    

    相关文章

      网友评论

        本文标题:MongoDB的集合操作

        本文链接:https://www.haomeiwen.com/subject/zbocuqtx.html