Bài 10: MongoDB - chèn Document - MongoDB

Đăng bởi: Admin | Lượt xem: 1481 | Chuyên mục: SQL


1. Phương thức insert() 

Để chèn dữ liệu vào trong Collection trong MongoDB, bạn cần sử dụng phương thức insert() hoặc save().
Cú pháp
Cú pháp cơ bản của lệnh insert() như sau:
>db.COLLECTION_NAME.insert(document)
Ví dụ
> db.users.insert({
... _id : ObjectId("507f191e810c19729de860ea"),
... title: "MongoDB Overview",
... description: "MongoDB is no sql database",
... by: "tutorials point",
... url: "http://www.tutorialspoint.com",
... tags: ['mongodb', 'database', 'NoSQL'],
... likes: 100
... })
WriteResult({ "nInserted" : 1 })
>
Ở đây, mycol là tên của Collection, đã được tạo trong chương trước. Nếu Collection này chưa tồn tại trong cơ sở dữ liệu, thì MongoDB sẽ tạo Collection này và sau đó chèn Document vào trong nó.
Trong Document được chèn, nếu chúng ta không xác định tham số _id, thì MongoDB gán một ObjectId duy nhất cho Document này.
_id là một số thập lục phân duy nhất, dài 12 byte cho mỗi Document trong một Collection. 12 byte được phân chia như sau (đã được mô tả trong các chương trước):
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)
Để chèn nhiều Document trong một truy vấn đơn, bạn có thể truyền một mảng các Document trong lệnh insert().
Ví dụ
> db.createCollection("post")
> db.post.insert([
	{
		title: "MongoDB Overview",
		description: "MongoDB is no SQL database",
		by: "tutorials point",
		url: "http://www.tutorialspoint.com",
		tags: ["mongodb", "database", "NoSQL"],
		likes: 100
	},
	{
	title: "NoSQL Database",
	description: "NoSQL database doesn't have tables",
	by: "tutorials point",
	url: "http://www.tutorialspoint.com",
	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" : [ ]
})
>
Để chèn dữ liệu vào trong Document, bạn cũng có thể sử dụng db.post.save(document). Nếu bạn không xác định _id trong Document, thì phương thức save() sẽ làm việc giống như phương thức insert(). Nếu bạn xác định _id, thì nó sẽ thay thế toàn bộ dữ liệu của Document chứa _id khi được xác định trong phương thức save().

2. Phương thức insertOne()

Nếu bạn chỉ cần chèn duy nhất 1 thư viện vào collection , bạn có thể sử dụng phương thức này
Cú pháp :
>db.COLLECTION_NAME.insertOne(document)
Ví dụ :
Ví dụ sau đây sẽ tạo 1 collection mới empDetails và sử dụng 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")
}
>

3. Phương thức insertMany()

Ta có thể chèn nhiều thư viện bằng cách sử dụng phương thức insertMany().Để sử dụng thư viện này, bạn cần đưa mảng vào thư viện
Ví dụ :
Ở ví dụ dưới đây sẽ thêm 3 thư viện khác nhau vào empDetails sử dụng phương thức insertMany()
> 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")
	]
}
>
Bài tiếp theo: MongoDB - truy vấn Document >>
vncoder logo

Theo dõi VnCoder trên Facebook, để cập nhật những bài viết, tin tức và khoá học mới nhất!