db.collection_name.insert(document)
db.collection_name.save(document)
> db.user.insert([ ... { ... name:"张三", ... phone:"15012345678" ... },{ ... name:"李四", ... phone:"18687654321" ... },{ ... name:"王五", ... phone:"13100001111" ... } ... ]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })文档插入成功后您可以使用 find() 方法来查看集合中文档的内容,如下所示:
> db.user.find() { "_id" : ObjectId("6030d907d029695c0c340c43"), "name" : "张三", "phone" : "15012345678" } { "_id" : ObjectId("6030d907d029695c0c340c44"), "name" : "李四", "phone" : "18687654321" } { "_id" : ObjectId("6030d907d029695c0c340c45"), "name" : "王五", "phone" : "13100001111" }文档中 _id 为主键 ID,它在每个文档中都是唯一的,在插入文档时,如果不指定 _id,MongoDB 则会为此文档自动分配一个唯一的 _id,当然您也可以手动定义 _id 的值。
db.collection_name.insertOne(document)
【示例】使用 insertOne() 方法向集合中插入一个文档:> db.user.insertOne({ ... title:"编程帮", ... url:"www.lmcjl.com", ... course:"MongoDB教程" ... }) { "acknowledged" : true, "insertedId" : ObjectId("6030d6c4d029695c0c340c42") } > db.user.find() { "_id" : ObjectId("6030d6c4d029695c0c340c42"), "title" : "编程帮", "url" : "www.lmcjl.com", "course" : "MongoDB教程" }
> db.user.insertMany([ ... { ... name:"张三", ... phone:"15012345678" ... },{ ... name:"李四", ... phone:"18611112222" ... },{ ... name:"王五", ... phone:"13166668888" ... } ... ]) { "acknowledged" : true, "insertedIds" : [ ObjectId("6030dbf2d029695c0c340c46"), ObjectId("6030dbf2d029695c0c340c47"), ObjectId("6030dbf2d029695c0c340c48") ] } > db.user.find() { "_id" : ObjectId("6030dbf2d029695c0c340c46"), "name" : "张三", "phone" : "15012345678" } { "_id" : ObjectId("6030dbf2d029695c0c340c47"), "name" : "李四", "phone" : "18611112222" } { "_id" : ObjectId("6030dbf2d029695c0c340c48"), "name" : "王五", "phone" : "13166668888" }
本文链接:http://task.lmcjl.com/news/17646.html