在本章中,我們將學習如何在MongoDB集合中插入文檔。
要將數(shù)據(jù)插入MongoDB集合,您需要使用MongoDB的insert() 或 save()方法。
insert()命令的基本語法如下-
>db.COLLECTION_NAME.insert(document)
> db.users.insert({ ... _id : ObjectId("507f191e810c19729de860ea"), ... title: "MongoDB Overview", ... description: "MongoDB is no sql database", ... by: "基礎教程", ... url: "", ... tags: ['mongodb', 'database', 'NoSQL'], ... likes: 100 ... }) WriteResult({ "nInserted" : 1 }) >
這是我們在上一章中創(chuàng)建的集合名稱 mycol 。如果數(shù)據(jù)庫中不存在該集合,則MongoDB將創(chuàng)建此集合,然后將文檔插入其中。
在插入的文檔中,如果不指定_id參數(shù),則MongoDB會為此文檔分配一個唯一的ObjectId。
_id是12字節(jié)的十六進制數(shù)字,對于集合中的每個文檔都是唯一的。12字節(jié)被劃分如下:
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
還可以將文檔數(shù)組傳遞到insert()方法,如下所示:
> db.createCollection("post") > db.post.insert([ { title: "MongoDB Overview", description: "MongoDB不是SQL數(shù)據(jù)庫", by: "基礎教程", url: "", tags: ["mongodb", "database", "NoSQL"], likes: 100 }, { title: "NoSQL Database", description: "NoSQL數(shù)據(jù)庫沒有表", by: "基礎教程", url: "", tags: ["mongodb", "database", "NoSQL"], likes: 20, comments: [ { user:"user1", message: "My first comment", dateCreated: new Date(2013,11,10,2,35), like: 0 } ] } ]) BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 2, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] }) >
要插入文檔,您也可以使用db.post.save(document)。如果您未在文檔中指定 _id,則 save()方法將與insert()方法相同。如果指定_id,則它將替換save()方法中指定的包含_id的文檔的整個數(shù)據(jù)。
如果只需要將一個文檔插入到集合中,則可以使用此方法。
insertOne()命令的基本語法如下:
>db.COLLECTION_NAME.insertOne(document)
以下示例創(chuàng)建一個名為 empDetails 的新集合,并使用insertOne()方法插入一個文檔。
> db.createCollection("empDetails") { "ok" : 1 }
> db.empDetails.insertOne( { First_Name: "Radhika", Last_Name: "Sharma", Date_Of_Birth: "1995-09-26", e_mail: "radhika_sharma.123@gmail.com", phone: "9848022338" }) { "acknowledged" : true, "insertedId" : ObjectId("5dd62b4070fb13eec3963bea") } >
您可以使用insertMany()方法插入多個文檔。對于此方法,您需要傳遞一個文檔數(shù)組。
以下示例使用insertMany()方法將三個不同的文檔插入empDetails集合。
> db.empDetails.insertMany( [ { First_Name: "Radhika", Last_Name: "Sharma", Date_Of_Birth: "1995-09-26", e_mail: "radhika_sharma.123@gmail.com", phone: "9000012345" }, { First_Name: "Rachel", Last_Name: "Christopher", Date_Of_Birth: "1990-02-16", e_mail: "Rachel_Christopher.123@gmail.com", phone: "9000054321" }, { First_Name: "Fathima", Last_Name: "Sheik", Date_Of_Birth: "1990-02-16", e_mail: "Fathima_Sheik.123@gmail.com", phone: "9000054321" } ] ) { "acknowledged" : true, "insertedIds" : [ ObjectId("5dd631f270fb13eec3963bed"), ObjectId("5dd631f270fb13eec3963bee"), ObjectId("5dd631f270fb13eec3963bef") ] } >