mongodb基础操作
创建操作
单个创建
db.collection.insertOne(
<document>,
{writeConcern: <document>}
)
writeConcern定义了本此文档创建操作的安全写级别- 安全写级别用来判断一次数据库写入操作是否成功
- 安全写界别越高,丢失数据的风险就越低,然而写入操作的延迟也越高
- 如果不提供
writeConcern文档,mongoDB使用默认的安全写级别 db不事先指定的话,会默认新建test库,并在其上进行操作
无需在创建文档前新建collection,insertOne命令会自动创建相应的集合。
document中可包含_id属性,用以替代自带的主键(非数组形式)。如果不提过_id属性,mongodb将会自动生成主键ObjectID
mongodb中可使用复合主键,_id可为文档形式。此时主键的唯一性指的_id的绝对唯一性,包含文档的字段顺序。如{_id: {a: '11', b: '22'}}与{_id: {b: '22',a: '11'}}是不会发生主键重复错误的
返回结果:
{acknowledged: true, insertedId: xxxx-xxxx-xxxx-xxxx}
aknowledged: true表示安全写级别被启用insertedId显示被写入文档的_id
插入操作也有存在发生错误的情况,如重复主键。此时可以直接在mongo shell中使用try catch进行错误的获取:
try{
db.collection.insertOne(
document
)
}catch(err) {
print(err)
}
创建单个文档也可以使用save命令,其本质还是调用insertOne命令,特性与其一致
多个创建
db.collection.insertMany(
[<document1>, <document2>,...],
{
writeConcern: <document>,
ordered: <boolean>
}
)
ordered参数用来判断mongodb是否要按照顺序对这些文档进行插入,默认为true。如果设置为false,则会不按照顺序进行插入,会提高插入性能- 当
ordered参数默认设置为true时,insertMany操作会按顺序进行文档插入操作,遇到插入错误的文档就会退出,后面无论正确与否,都不会写入 - 当
ordered参数设置为false时,insertMany操作不会按照顺序进行插入,即使某些文档造成错误,剩余的正确文档仍然会被写入
返回值:
{acknowledged: true, insertedIds: [xxxx-xxxx-xxxx-xxxx, xxxx-xxxx-xxxx-xxxx]}
返回两个主键值与acknowledged
既可以单个,也可以多个
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
返回结果:
- 当插入单个文档时,返回
WriteResult({ "nInserted" : 1 }) - 当插入多条文档时,返回
BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })

浙公网安备 33010602011771号