Bài 11: MongoDB - truy vấn Document - MongoDB

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


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

Để truy vấn dữ liệu từ Collection trong MongoDB, bạn cần sử dụng phương thức find() trong MongoDB.
Cú pháp
Cú pháp cơ bản của phương thức find() là như sau:
>db.COLLECTION_NAME.find()
Phương thức find() sẽ hiển thị tất cả Document ở dạng không có cấu trúc (hiển thị không theo cấu trúc nào).
Ví dụ :
Giả sử chúng ta đã tạp collection với tên là mycol như sau :
> use sampleDB
switched to db sampleDB
> db.createCollection("mycol")
{ "ok" : 1 }
>
Chèn 3 document sử dụng phương thức insert() 
> db.mycol.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
			}
		]
	}
])
Phương thức sau truy xuất tất cả các tài liệu trong document
> db.mycol.find()
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview", "description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" : "http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "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" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] }
>

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

Để hiển thị các kết quả theo một cách đã được định dạng, bạn có thể sử dụng phương thức pretty().
Cú pháp
>db.mycol.find().pretty()
Ví dụ
> db.mycol.find().pretty()
{
	"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
	"title" : "MongoDB Overview",
	"description" : "MongoDB is no SQL database",
	"by" : "tutorials point",
	"url" : "http://www.tutorialspoint.com",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 100
}
{
	"_id" : ObjectId("5dd4e2cc0821d3b44607534d"),
	"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" : ISODate("2013-12-09T21:05:00Z"),
			"like" : 0
		}
	]
}
Ngoài phương thức find(), trong MongoDB còn có phương thức findOne() sẽ chỉ trả về một Document.

3. Phương thức findOne():

Là 1 phần của phương thức find(), đó là phương thức findOne(), nó chỉ trả về 1 document
Cú pháp :
>db.COLLECTIONNAME.findOne()
Ví dụ:
> db.mycol.findOne({title: "MongoDB Overview"})
{
	"_id" : ObjectId("5dd6542170fb13eec3963bf0"),
	"title" : "MongoDB Overview",
	"description" : "MongoDB is no SQL database",
	"by" : "tutorials point",
	"url" : "http://www.tutorialspoint.com",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 100
}

4. Truy vấn trong MongoDB mà tương đương mệnh đề WHERE trong RDBMS

Để truy vấn Document dựa trên một số điều kiện nào đó, bạn có thể sử dụng các phép toán sau:
Phép toánCú phápVí dụMệnh đề WHERE tương đương
Equality{<key>:<value>}
db.mycol.find({"by":"tutorials point"}).pretty()
where by = 'tutorials point'
Less Than{<key>:{$lt:<value>}}
db.mycol.find({"likes":{$lt:50}}).pretty()
where likes < 50
Less Than Equals
{<key>:{$lte:<value>}}
db.mycol.find({"likes":{$lte:50}}).pretty()
where likes <= 50
Greater Than{<key>:{$gt:<value>}}
db.mycol.find({"likes":{$gt:50}}).pretty()
where likes > 50
Greater Than Equals
{<key>:{$gte:<value>}}
db.mycol.find({"likes":{$gte:50}}).pretty()
where likes >= 50
Not Equals
{<key>:{$ne:<value>}}
db.mycol.find({"likes":{$ne:50}}).pretty()
where likes != 50

5. AND trong MongoDB

Cú pháp
Trong phương thức find(), nếu bạn truyền nhiều key bằng cách phân biệt chúng bởi dấu phảy (,), thì MongoDB xem nó như là điều kiện AND. Cú pháp cơ bản của AND trong MongoDB như sau:
>db.mycol.find({key1:value1, key2:value2}).pretty()
Ví dụ
Ví dụ sau hiển thị tất cả loạt bài hướng dẫn (tutorials) được viết bởi 'tutorials point' có title là 'MongoDB Overview'
> db.mycol.find({$and:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
	"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
	"title" : "MongoDB Overview",
	"description" : "MongoDB is no SQL database",
	"by" : "tutorials point",
	"url" : "http://www.tutorialspoint.com",
	"tags" : [
		"mongodb",
		"database",
		"NoSQL"
	],
	"likes" : 100
}
>
Mệnh đề WHERE tương đương với ví dụ trên sẽ là ' where by='tutorials point' AND title='MongoDB Overview' '. Bạn có thể truyền bất kỳ số cặp key-value nào trong mệnh đề find.

6. OR trong MongoDB

Cú pháp
Để truy vấn Document dựa trên điều kiện OR, bạn cần sử dụng từ khóa $or. Cú pháp cơ bản của OR trong MongoDB như sau:
>db.mycol.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()
Ví dụ
Ví dụ sau sẽ hiển thị tất cả loạt bài hướng dẫn (tutorials) được viết bởi 'tutorials point' hoặc có title là 'MongoDB Overview'
>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

7. Sử dụng AND và OR cùng nhau trong MongoDB

Ví dụ
Ví dụ sau hiển thị các Document mà có các like lớn hơn 100 và có title là hoặc 'MongoDB Overview' hoặc bởi là 'tutorials point'. Mệnh đề WHERE trong truy vấn SQL tương đương là 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'
Ví dụ :
>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"},
   {"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "tutorials point",
   "url": "http://www.tutorialspoint.com",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
>

8. NOR in MongoDB

Cú pháp
Để truy vấn document dựa vào điều kiện NOT, bạn cần sử dụng keyword $not như sau :
>db.COLLECTION_NAME.find(
	{
		$not: [
			{key1: value1}, {key2:value2}
		]
	}
)
Ví dụ :
Giả sử ta chèn 3 documents vào empDetails :
db.empDetails.insertMany(
	[
		{
			First_Name: "Radhika",
			Last_Name: "Sharma",
			Age: "26",
			e_mail: "radhika_sharma.123@gmail.com",
			phone: "9000012345"
		},
		{
			First_Name: "Rachel",
			Last_Name: "Christopher",
			Age: "27",
			e_mail: "Rachel_Christopher.123@gmail.com",
			phone: "9000054321"
		},
		{
			First_Name: "Fathima",
			Last_Name: "Sheik",
			Age: "24",
			e_mail: "Fathima_Sheik.123@gmail.com",
			phone: "9000054321"
		}
	]
)
Ví dụ sau sẽ truy xuất (các) tài liệu có tên không phải là "Radhika" và họ không phải là "Christopher"
> db.empDetails.find(
	{
		$nor:[
			40
			{"First_Name": "Radhika"},
			{"Last_Name": "Christopher"}
		]
	}
).pretty()
{
	"_id" : ObjectId("5dd631f270fb13eec3963bef"),
	"First_Name" : "Fathima",
	"Last_Name" : "Sheik",
	"Age" : "24",
	"e_mail" : "Fathima_Sheik.123@gmail.com",
	"phone" : "9000054321"
}

9. NOT in MongoDB:

Cú pháp
>db.COLLECTION_NAME.find(
	{
		$NOT: [
			{key1: value1}, {key2:value2}
		]
	}
).pretty()
Ví dụ :
> db.empDetails.find( { "Age": { $not: { $gt: "25" } } } )
{
	"_id" : ObjectId("5dd6636870fb13eec3963bf7"),
	"First_Name" : "Fathima",
	"Last_Name" : "Sheik",
	"Age" : "24",
	"e_mail" : "Fathima_Sheik.123@gmail.com",
	"phone" : "9000054321"
}
Bài tiếp theo: MongoDB - Cập nhật 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!