插入
db.集合名称.insert(document)
> use mongotest
switched to db mongotest
> db.user.insert({"user_name":"zhangsan", "sex": "man"})
WriteResult({ "nInserted" : 1 })
> db.user.insert({"user_name": "zhangsan", "sex": "man","age": 18, "bank_info": {"bank_code": "9941257632544000", "bank_name": "Bank Of China"}})
WriteResult({ "nInserted" : 1 })
> db.user.find()
{ "_id" : ObjectId("5c99ceaf772e53bfa80bcfa4"), "user_name" : "zhangsan", "sex" : "man" }
{ "_id" : ObjectId("5c99cfa4772e53bfa80bcfa5"), "user_name" : "zhangsan", "sex" : "man", "age" : 18, "bank_info" : { "bank_code" : "9941257632544000", "bank_name" : "Bank Of China" } }
>
不指定_id,mongodb会自动为插入文档创建_id,类型为Object ID类型,若要指定_id,只需要在插入document中指定即可,
由于_id具有唯一性,所以当执行insert插入操作时,若_id已存在,则抛出异常
> db.user.remove({}) # 清空集合数据
WriteResult({ "nRemoved" : 0 })
> db.user.insert({"_id": 10086,"user_name":"zhangsan", "sex": "man"}) # 第一次插入
WriteResult({ "nInserted" : 1 }) # 插入成功
> db.user.find()
{ "_id" : 10086, "user_name" : "zhangsan", "sex" : "man" }
> db.user.insert({"_id": 10086,"user_name":"zhangsan", "sex": "man"}) # 第二次插入(_id相同)错误异常 _id重复
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error