数据库操作
# 查看数据库列表
show dbs;
# 查看当前所在数据库
db;
# 数据库切换,如果不存在的话,会自动创建
use test;
# 查看数据库中的集合
show collections;
创建单个文档之insertOne
# accounts 是集合名称,如果不存在的话,会自动创建
db.accounts.insertOne({
_id:"account1",
name:"alice",
balance:100
})
# 成功的返回值,acknowledged 为true,表示安全级别被启用,insertedId 为插入的新纪录的ID。
{ "acknowledged" : true, "insertedId" : "account1" }
# 如果我们插入的数据_id重复,就会报错。
2019-09-16T05:58:37.113+0000 E QUERY [js] WriteError({......})
# 如果我们插入的数据,没有自定义_id字段,则会自动生成文档主键
创建多个文档之insertMany
- ordered 默认为true,即顺序写入。设置为false的时候,表示乱序写入,可以提高操作性能。
- 假如批量插入多条数据的话,ordered 为 true,则插入过程中报错的话,后面的插入就会中断
- 假如批量插入多条数据的话,ordered 为false,则插入过程中报错的话,后面的插入会照常执行
db.accounts.insertMany([ { "name" : "charlie", "balance" : 500 }, { "name" : "david", "balance" : 200 } ],{ ordered:false })
# {"acknowledged" : true,"insertedIds" : [ObjectId("5d7f25f4aecbd2bc0fa821b3"),ObjectId("5d7f25f4aecbd2bc0fa821b4")]}
创建文档全能选手之insert
使用insert
命令,既可插入单个、也可插入多个文档。
insertOne
和 insertMany
命令不支持 db.collection.explain()
命令,但是 insert
支持
1. 单条
单条插入成功
db.accounts.insert({ name:"alice2", balance:100 })
WriteResult({ "nInserted" : 1 })
单条插入失败
db.accounts.insert({ _id:"account1", name:"alice", balance:100 })
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.accounts index: _id_ dup key: { _id: \"account1\" }"
}
})
2. 多条
全部成功
db.accounts.insert([ { "name" : "charlie", "balance" : 500 }, { "name" : "david", "balance" : 200 } ],{ ordered:false })
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
部分成功
> db.accounts.insert([ { _id:"account1","name" : "charlie", "balance" : 500 }, { "name" : "david", "balance" : 200 } ],{ ordered:false })
BulkWriteResult({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.accounts index: _id_ dup key: { _id: \"account1\" }",
"op" : {
"_id" : "account1",
"name" : "charlie",
"balance" : 500
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 1,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
全部失败
db.accounts.insert([ { _id:"account1","name" : "charlie", "balance" : 500 }, { "name" : "david", "balance" : 200 } ],{ ordered:true })
BulkWriteResult({
"writeErrors" : [
{
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.accounts index: _id_ dup key: { _id: \"account1\" }",
"op" : {
"_id" : "account1",
"name" : "charlie",
"balance" : 500
}
}
],
"writeConcernErrors" : [ ],
"nInserted" : 0,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})