介绍
mongodb 中的 文档(document),相当于 关系型数据库的 一行记录(row)
我们看到的 文档(document)数据结构,与 JSON 基本一样
但存储在 集合 中的数据都是 BSON 格式,BSON:二进制的JSON
单个文档插入
向 集合 插入一个记录,如果集合 不存在 则 创建集合
db.集合名.insert(
类似json格式的数据
)
例子
db.user.insert(
{
"_id":"1",
"username":"lilei",
"password":"123456",
"name":"李雷",
"sex":"男",
"age":NumberInt(20),
"createtime":new Date()
}
)
执行结果:
WriteResult({ "nInserted" : 1 })
主键
- 插入的数据没有指定
_id,会 自动生成主键值 - 指定了
_id,则主键就是该值
说明
- 集合如果不存在,则会隐式创建
- mongo中的数字,默认情况下是 double类型。如果要存 整型,必须使用函数
NumberInt(整型数字),否则取出来就有问题 - 插入当前日期使用
new Date() - 如果某字段没值,可以赋值为
null,或 不写该字段
注意
- 文档中的 键/值对 是 有序 的
- 文档中的值不仅可以是在双引号里面的字符串,还可以是其他几种数据类型(甚至可以是整个嵌入的文档)。
- 区分 类型 和 大小写
- 一个文档不能有 重复的键
- 文档的 键是字符串。除了少数例外情况,键可以使用任意UTF-8字符。
文档键命名规范
- 键不能含有 空字符。这个字符用来表示键的结尾。
.和$有特别的意义,只有在特定环境下才能使用- 以下划线
_开头的键是保留的(不是严格要求的)
多个文档批量插入
db.集合名.insertMany(
类似json数组格式的数据
)
注意: 如果某条数据插入失败,将会 终止插入,但已经插入成功的数据 不会回滚
例子
db.common.insertMany(
[{
"_id":"1",
"content":"mongodb好用",
"authorid":"1",
"like":NumberInt(1),
"createtime":new Date()
},{
"_id":"2",
"content":"mongodb不错",
"authorid":"2",
"like":NumberInt(2),
"createtime":new Date()
}]
)
执行结果:
{ "acknowledged" : true, "insertedIds" : [ "1", "2" ] }
try…catch
因为批量插入多条数据,容易失败,因此,可以使用 try...catch 进行异常捕捉处理
try{
db.common.insertMany(
[{
"_id":"5",
"content":"mongodb好用",
"authorid":"1",
"like":NumberInt(1),
"createtime":new Date()
},{
"_id":"2",
"content":"mongodb不错",
"authorid":"2",
"like":NumberInt(2),
"createtime":new Date()
}]
)
} catch (e) {
print (e);
}
执行报错如下:
BulkWriteError({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: blog.common index: _id_ dup key: { : \"1\" }",
"op" : {
"_id" : "1",
"content" : "mongodb好用",
"authorid" : "1",
"like" : NumberInt(1),
"createtime" : ISODate("2021-08-08T09:11:38.451Z")
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})