MongoDB - 插入文件



本章我們將學習如何在 MongoDB 集合中插入文件。

insert() 方法

要將資料插入 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: "tutorials point",
... url: "https://tutorialspoint.tw",
... tags: ['mongodb', 'database', 'NoSQL'],
... likes: 100
... })
WriteResult({ "nInserted" : 1 })
>

這裡 mycol 是我們的集合名稱,如前一章所建立。如果資料庫中不存在該集合,則 MongoDB 將建立此集合,然後向其中插入文件。

在插入的文件中,如果我們沒有指定 _id 引數,則 MongoDB 會為該文件分配一個唯一的 ObjectId。

_id 是一個 12 位元組的十六進位制數字,對於集合中的每個文件都是唯一的。12 位元組的劃分如下:

_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

您還可以將文件陣列傳遞到 insert() 方法中,如下所示:

> db.createCollection("post")
> db.post.insert([
	{
		title: "MongoDB Overview",
		description: "MongoDB is no SQL database",
		by: "tutorials point",
		url: "https://tutorialspoint.tw",
		tags: ["mongodb", "database", "NoSQL"],
		likes: 100
	},
	{
	title: "NoSQL Database",
	description: "NoSQL database doesn't have tables",
	by: "tutorials point",
	url: "https://tutorialspoint.tw",
	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 的文件的全部資料。

insertOne() 方法

如果您只需要向集合中插入一個文件,可以使用此方法。

語法

insert() 命令的基本語法如下:

>db.COLLECTION_NAME.insertOne(document)

示例

以下示例建立一個名為 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() 方法

您可以使用 insertMany() 方法插入多個文件。對於此方法,您需要傳遞一個文件陣列。

示例

以下示例使用 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")
	]
}
>
廣告