插入数据
文档是mongodb数据的基本单元,且对数据没有具体的模式要求,可以嵌套各种复杂的数据结构。
mongodb和关系数据库的对比:documents/collection/db----row/table/database
Create Collection:如果collection不存在, 那么insert()方法会自动创建collection
_id Field:每一个collection都会存在_id,如果不指定 _id值 mongodb会自动分配,且 _id 值需要唯一,以免发生重复报错
插入数方法db.collection.insert():
插入一条嵌套数据:
db.stuff.insert( { name:"mark", age:25, interests:{ books:["战争与和平","西游记"] ,news:{economi:["华尔街日报","第一财经日报"],sports:["NBA","体育周报","足球"]} } } )
插入多条数据:
db.stuff.insert( [ {name:"mike",age:30,sex:"male",interests:"football"}, {name:"lily",age:28,sex:"female",interests:"watch TV"} ] )
插入多条数据:
var stufflist=[ {name:"tony",age:30,sex:"male",interests:"movie"}, {name:"jack",age:23,sex:"male",interests:"program"} ] db.stuff.insert(stufflist)
可以使用db.stuff.find()查看插入的数据如下;
{ "_id" : ObjectId("54a652ea1e123c5494de5bda"), "name" : "mark", "age" : 25, "interests" : { "books" : [ "战争与和平", "西游记" ], "news" : { "economi" : [ "华尔街日报", "第一财经日报" ], "sports" : [ "NBA", "体育周报", "足球" ] } } } { "_id" : ObjectId("54a654951e123c5494de5bdb"), "name" : "mike", "age" : 30, "sex" : "male", "interests" : "football" } { "_id" : ObjectId("54a654951e123c5494de5bdc"), "name" : "lily", "age" : 28, "sex" : "female", "interests" : "watch TV" } { "_id" : ObjectId("54a655771e123c5494de5bdd"), "name" : "tony", "age" : 30, "sex" : "male", "interests" : "movie" } { "_id" : ObjectId("54a655771e123c5494de5bde"), "name" : "jack", "age" : 23, "sex" : "male", "interests" : "program" }