创建文档时,如果集合不存在会自动创建集合

insertOne

说明

创建单个文档.命令格式为db.collection.insertOne().具体参数如下:
db.<collection>.insertOne(  # <collection> 需要写入的集合
    <document>, # 写入的文档内容
    { # 非必选
      writeConcern: <document> # 写入集合的安全级别,默认为mongoDB默认的安全写级别
    }
)

示例

创建自定义主键文档

自定义主键一定要保证其唯一性.不可重复

# 使用数据库,没有自动创建
> use qvbilam 
switched to db qvbilam

# 创建自定义主键的文档
> db.qvbilam_user.insertOne(
...  {
...     _id: 'qvbilam_01',    # 文档主键id
...     name: 'angelQvbilam', 
...     num: 10
...  }
... )
# 返回内容
{ "acknowledged" : true, "insertedId" : "qvbilam_01" } # 安全写级别启动, 主键id为自定义的id

当创建的主键id重复时

# 创建重复的主键id时
> db.qvbilam_user.insertOne(
...  {
...    _id: 'qvbilam_01',
...    name: 'qvbilam',
...    num:21
...  }
... )

异常

WriteError({
    "index" : 0,
    "code" : 11000,
    "errmsg" : "E11000 duplicate key error collection: test.qvbilam_user index: _id_ dup key: { _id: \"qvbilam_01\" }",
    "op" : {
        "_id" : "qvbilam_01",
        "name" : "qvbilam",
        "num" : 21
    }
}) :
WriteError({
    "index" : 0,
    "code" : 11000,
    "errmsg" : "E11000 duplicate key error collection: test.qvbilam_user index: _id_ dup key: { _id: \"qvbilam_01\" }",
    "op" : {
        "_id" : "qvbilam_01",
        "name" : "qvbilam",
        "num" : 21
    }
})
WriteError@src/mongo/shell/bulk_api.js:458:48
mergeBatchResults@src/mongo/shell/bulk_api.js:855:49
executeBatch@src/mongo/shell/bulk_api.js:919:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1163:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:264:9
@(shell):1:1

创建系统生成主键的文档

  只需要忽略文档中的_id字段即可.如下:

> db.qvbilam_user.insertOne(
...  {
...    name: "GuoOne",
...    num : 32
...  }
... )
# 返回如下
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5f38c3321aac6647ce0f2736") # 系统自动生成的主键id
}

insertMany

说明

创建多个文档.命令格式为db.collection.insertMony().具体参数如下:
db.<collection>.insertMoney(
  [<document><document>,...], # 多个文档的集合
  {
    writeConern: <document>, # 安全写级别
    ordered: <boolean> # 是否按顺序写文档
  }
)

示例

按顺序插入文档

# 创建两个文档
> db.qvbilam_user.insertMany([
...  {
...    name: "GuoTwo",
...    num: 12,
...  },
...  {
...    name: "GuoThree",
...    num: 13,
...  }
... ])
# 返回的主键id为一个集合
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5f38c4ff1aac6647ce0f2737"),
        ObjectId("5f38c4ff1aac6647ce0f2738")
    ]
}

按顺序插入错误文档

> db.qvbilam_user.insertMany([
...  {
...    _id: "qvbilam_01",
...    name: "errorName",
...    num: 1,
...  },
...  {
...    name: "Hello",
...    num: 13,
...  }
... ])

返回异常

uncaught exception: BulkWriteError({
    "writeErrors" : [
        {
            "index" : 0,
            "code" : 11000,
            "errmsg" : "E11000 duplicate key error collection: test.qvbilam_user index: _id_ dup key: { _id: \"qvbilam_01\" }",
            "op" : {
                "_id" : "qvbilam_01",
                "name" : "errorName",
                "num" : 1
            }
        }
    ],
    "writeConcernErrors" : [ ],
    "nInserted" : 0,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
}) :
BulkWriteError({
    "writeErrors" : [
        {
            "index" : 0,
            "code" : 11000,
            "errmsg" : "E11000 duplicate key error collection: test.qvbilam_user index: _id_ dup key: { _id: \"qvbilam_01\" }",
            "op" : {
                "_id" : "qvbilam_01",
                "name" : "errorName",
                "num" : 1
            }
        }
    ],
    "writeConcernErrors" : [ ],
    "nInserted" : 0,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})
BulkWriteError@src/mongo/shell/bulk_api.js:367:48
BulkWriteResult/this.toError@src/mongo/shell/bulk_api.js:332:24
Bulk/this.execute@src/mongo/shell/bulk_api.js:1186:23
DBCollection.prototype.insertMany@src/mongo/shell/crud_api.js:326:5
@(shell):1:1

不按顺序批量插入

在上述按顺序批量插入文档可以看到当出现错误,后面的文档不会继续执行.在返回的错误中有一列为插入为0条"nInserted" : 0,下面试试不按顺序批量插入错误的文档.可以总结出.如果不按顺序进行插入文档的情况下:在第一条文档出现错误,后面的文档没有出现错误的情况下.mongoDB会把正确的文档写入到集合中.

# 插入3条文档,其中第一条文档为主键重复的.插入方式为不按顺序插入
db.qvbilam_user.insertMany([
 {
   _id: "qvbilam_01",
   name: "test",
   num: 13  
 },
 {
   name: "GuoTwo",
   num: 13
 },
 {
   name: "GuoThree", 
   num: 14
 }
],
 {
   ordered:false
 }
)

返回异常

uncaught exception: BulkWriteError({
    "writeErrors" : [
        {
            "index" : 0,
            "code" : 11000,
            "errmsg" : "E11000 duplicate key error collection: qvbilam.qvbilam_user index: _id_ dup key: { _id: \"qvbilam_01\" }",
            "op" : {
                "_id" : "qvbilam_01",
                "name" : "test",
                "num" : 13
            }
        }
    ],
    "writeConcernErrors" : [ ],
    "nInserted" : 2,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
}) :
BulkWriteError({
    "writeErrors" : [
        {
            "index" : 0,
            "code" : 11000,
            "errmsg" : "E11000 duplicate key error collection: qvbilam.qvbilam_user index: _id_ dup key: { _id: \"qvbilam_01\" }",
            "op" : {
                "_id" : "qvbilam_01",
                "name" : "test",
                "num" : 13
            }
        }
    ],
    "writeConcernErrors" : [ ],
    "nInserted" : 2,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})
BulkWriteError@src/mongo/shell/bulk_api.js:367:48
BulkWriteResult/this.toError@src/mongo/shell/bulk_api.js:332:24
Bulk/this.execute@src/mongo/shell/bulk_api.js:1186:23
DBCollection.prototype.insertMany@src/mongo/shell/crud_api.js:326:5
@(shell):1:1

insert

说明

可以创建单个,或多个文档.命令格式为db.collection.insert().具体参数如下:
db.<collection>.insert(  # <collection> 需要写入的集合
    <document> or [<document1>,<document2>,...], # 写入的文档内容
    { # 非必选
      writeConcern: <document> # 写入集合的安全级别,默认为mongoDB默认的安全写级别
    ordered: <boolean> # 是否按顺序写入
    }
)

示例

使用insert插入单条/多条与insertOne/insertMany命令的返回参数进行对比.返回结过是不相同的.

插入单条文档

插入成功

# 插入成功
> db.qvbilam_user.insert(
...  {
...    name: "PEPSI",
...    num: 20
...  }
... )

# 插入成功返回内容
WriteResult({ "nInserted" : 1 })  # 与insertOne命令返回的内容是不一样的.

插入失败

# 插入失败
> db.qvbilam_user.insert(
...  {
...    _id: "qvbilam_01",
...    name: "test",
...    num: 13
...  }
... )

# 插入失败异常
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: qvbilam.qvbilam_user index: _id_ dup key: { _id: \"qvbilam_01\" }"
    }
})

插入多条文档

插入成功

# 插入多条记录
> db.qvbilam_user.insert([
...  {
...    name: "Coca cola",
...    num: 13
...  },
...  {
...    name: "gy",
...    num: 12
...  }
... ])
# 插入成功返回
BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 2,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})

插入失败

# 插入多条记录
> db.qvbilam_user.insert([
...  {
...    _id: "qvbilam_01",
...    name: "zcx",
...    num: 13
...  },
...  {
...    name: "nb",
...    num: 14
...  }
... ])

# 异常
BulkWriteResult({
    "writeErrors" : [
        {
            "index" : 0,
            "code" : 11000,
            "errmsg" : "E11000 duplicate key error collection: qvbilam.qvbilam_user index: _id_ dup key: { _id: \"qvbilam_01\" }",
            "op" : {
                "_id" : "qvbilam_01",
                "name" : "zcx",
                "num" : 13
            }
        }
    ],
    "writeConcernErrors" : [ ],
    "nInserted" : 0,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})

save

说明

创建单个文档,当使用save命令后会调用insert.即返回结果与insert命令的返回结果相同.命令格式为db.collection.insertOne().具体参数如下:
db.<collection>.save(  # <collection> 需要写入的集合
    <document> or [<document1>,<document2>,...], # 写入的文档内容
    { # 非必选
      writeConcern: <document> # 写入集合的安全级别,默认为mongoDB默认的安全写级别
    }
)

示例

插入单条文档

# 插入单条文档
> db.qvbilam_user.save({
...   name: "save",
...   num: 12
... })

# 返回结果
WriteResult({ "nInserted" : 1 })

插入多条文档

# 插入多条文档
> db.qvbilam_user.save([
...  {
...    name: "save1",
...    num: 1,
...  },
...  {
...    name: "save2",
...    num: 2
...  }
... ])

# 返回结果与insert返回结果相同
BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 2,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})
Last modification:February 20th, 2021 at 10:02 am