【MongoDB】插入文档
存储在集合中的数据都是BSON格式,和JSON基本一样,BSON是一种类json的一种二进制形式的存储格式,简称Binary JSON。
如果集合不存在, insert() 方法会创建集合。
【语法】
1 |
db.collection.insert() |
1:已存在集合插入数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# 显示当前库中的所有集合 > show collections t1 t2 t3 t4 > # 集合t1中插入数据 > db.t1.insert({name:'zhangsan',age:25,sex:0}) WriteResult({ "nInserted" : 1 }) > # 显示插入的内容 > db.t1.find() { "_id" : ObjectId("598145c8c566b07b8733e776"), "name" : "zhangsan", "age" : 25, "sex" : 0 } > |
2:插入数据的同时创建集合
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# 当前库中集合情况 > show collections t1 t2 t3 t4 > # 向一个不存在的集合插入文档 > db.t.insert({name:'zhangsan',age:25,sex:0}) WriteResult({ "nInserted" : 1 }) > # 集合被创建 > show collections t t1 t2 t3 t4 > |
3:定义变量
1 2 3 4 5 6 7 8 9 10 |
> v1 = ({name:"lisi",age:22,sex:0}) { "name" : "lisi", "age" : 22, "sex" : 0 } > > db.t.insert(v1) WriteResult({ "nInserted" : 1 }) > > db.t.find() { "_id" : ObjectId("59814679c566b07b8733e777"), "name" : "zhangsan", "age" : 25, "sex" : 0 } { "_id" : ObjectId("598164a5c566b07b8733e778"), "name" : "lisi", "age" : 22, "sex" : 0 } > |
4:批量插入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
> db.t.insert( [ {name:"zhaosi"}, {name:"liuneng"}, {name:"daguo"} ] ) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) > db.t.find() { "_id" : ObjectId("59814679c566b07b8733e777"), "name" : "zhangsan", "age" : 25, "sex" : 0 } { "_id" : ObjectId("598164a5c566b07b8733e778"), "name" : "lisi", "age" : 22, "sex" : 0 } { "_id" : ObjectId("59816629c566b07b8733e779"), "name" : "zhaosi" } { "_id" : ObjectId("59816629c566b07b8733e77a"), "name" : "liuneng" } { "_id" : ObjectId("59816629c566b07b8733e77b"), "name" : "daguo" } > |