You are on page 1of 58

8/19/2020

Phần 4: Quản lý Database và Collection trong MongoDB

1. Database: create - drop


2. Collection: create - drop
3. Export - Import Collection
4. Export - Import Database
5. Datatypes

1. Database

a. Create Database
• Chạy file mongo.exe để mở MongoDB shell:
"C:\Program Files\MongoDB\Server\4.1\bin\mongo.exe"

1
8/19/2020

1. Database

a. Create Database (tt)


• Gõ exit khi muốn thoát khỏi MongoDB shell:

1. Database

a. Create Database (tt)


• Cú pháp để create/use một database:
> use DATABASE_NAME

o Ví dụ: Mở một database đã có (tên là local)

2
8/19/2020

1. Database

a. Create Database (tt)


• Create/use database:
> use DATABASE_NAME

o Ví dụ: Tạo database mới tên là db_test1

1. Database

a. Create Database (tt)


• Kiểm tra database nào đang sử dụng:
> db

3
8/19/2020

1. Database

a. Create Database (tt)


• Xóa màn hình:
> cls

• Xem các database đang có:


> show dbs

1. Database

a. Create Database (tt)


• Note 1: Để database vừa tạo được hiển thị trong list các
DB, cần insert ít nhất 1 document vào trong db đó.

• Ví dụ: db_test1 không xuất hiện trong list dbs

4
8/19/2020

1. Database

a. Create Database (tt)


• Ví dụ: insert document và db_test1 xuất hiện trong list dbs

10

1. Database

a. Create Database (tt)


• Ví dụ: insert document và db_test1 xuất hiện trong list dbs

11

5
8/19/2020

1. Database

a. Create Database (tt)


• Note 2: Database mặc định của MongoDB là test.
• Ví dụ: Chèn 1 document khi không mở database nào

12

1. Database

a. Create Database (tt)


• Note 2: Database mặc định của MongoDB là test.
• Ví dụ: Chèn 1 document khi không mở database nào

13

6
8/19/2020

1. Database

14

1. Database

a. Create Database (tt)


• Practice 1: Viết lệnh thực hiện các yêu cầu sau
• Tạo database tên là db_05CNTTX (X là số hiệu của lớp)
• Chèn document vào db vừa tạo, nội dung như sau:
• <họ tên>: <họ và tên sinh viên>
• <mã số>: <3 số cuối mã số sinh viên>
• document này nằm trong collections tên là Stud_Infor
• Show danh sách các database khả dụng
• Chuyển sang sử dụng database mặc định

15

7
8/19/2020

1. Database

b. Drop Database
• Drop a existing database:
> db.dropDatabase()
o Ví dụ: Tạo db mới tên là db_test3 và insert document vào đó

16

1. Database

b. Drop Database (tt)


o Ví dụ: Xóa database db_test3 vừa tạo

17

8
8/19/2020

1. Database

b. Drop Database (tt)


• Note 2: Nếu user đang không sử dụng db nào thì
MongoDB sẽ xóa db mặc định (test)

18

1. Database

b. Drop Database (tt)


• Practice 2: Viết lệnh thực hiện các yêu cầu sau
• Check the list of available databases
• Delete new database called <mydb>
• Check list of databases

19

9
8/19/2020

2. Collection

a. Create Collection
• Cú pháp cơ bản để tạo một collection:
> db.createCollection(name, options)
o name: tên gọi của collection muốn tạo
o Options: a document và được dùng để xác định cấu hình
(configuration) của collection.

Parameter Type Description


Name String Name of the collection to be created

Options Document (Optional) Specify options about memory


20 size and indexing

2. Collection

a. Create Collection
• Danh sách các tùy chọn (options):
Field Type Description (Optional)
True enable một collection giới hạn (một collection kích
thước cố định, tự động ghi đè các mục cũ nhất của nó khi đạt
capped Boolean
đến kích thước tối đa)
=> cần xác định tham số kích thước (size) nếu chọn true
True tự động tạo index trên trường _id
autoIndexId Boolean
Mặc định là false. (Không còn được dùng từ version 4.1)
Chỉ định kích thước tối đa ở dạng bytes cho một capped
size number collection.
Nếu capped là true cần chỉ định giá trị cho trường này
21
max number Chỉ định số lượng document tối đa trong capped collection

10
8/19/2020

2. Collection

a. Create Collection
o Ví dụ, tạo collection bằng cú pháp basic, không lựa chọn các
options.

22

2. Collection

a. Create Collection
• Cú pháp kiểm tra các collection đã tạo trong db hiện
hành:
> show collections

23

11
8/19/2020

2. Collection

a. Create Collection
o Ví dụ, tạo collection bằng cú pháp basic có chỉ định options

24

2. Collection

a. Create Collection
• Note: Mongo cho phép insert document mà không cần
tạo collection trước.

25

12
8/19/2020

2. Collection

a. Create Collection

26

2. Collection

b. Drop Collection
• Cú pháp xóa collection khỏi database:
> db.Collection_name.drop()
o Ví dụ, xóa collection tên là Collection4 khỏi database
db_MongoCourse

27

13
8/19/2020

2. Collection

b. Drop Collection
• Note: phương thức drop() trả về true nếu xóa thành
công, ngược lại thì trả về false

28

2. Collection

b. Drop Collection
• Cú pháp xem các documents của collection:
> db.Collection_name.find()
o Ví dụ, xem các documents của collection5 trong database
db_MongoCourse

29

14
8/19/2020

2. Collection
b. Drop Collection
• Hiển thị các documents của collection ở dạng chuỗi
JSON
> db.Collection_name.find().pretty()

30

2. Collection

• Practice 3: Viết lệnh thực hiện các yêu cầu sau


• Tạo database tên là MDB_Course2
• Sử dụng basic syntax để chèn 3 record thông tin vào collection
Users trong db trên, mỗi record chứa tên, mật khẩu, trạng thái
(active hay unactive)
• Hiển thị các document của collection Users
• xóa collection users
• Chèn 2 record thông tin khác vào users theo cách không basic

31 GO

15
8/19/2020

2. Collection

• Note 1: Có thể kết hợp notepad++,... trong insert dữ liệu


1. Viết dữ liệu ở dạng chuỗi JSON trên file (ví dụ notepad++)
2. Copy chuỗi dữ liệu
3. Trên MongoShell, gõ lệnh db.CollectionName.insert(
4. Click chuột phải
5. Đóng dấu ngoặc của hàm và chạy lệnh

32

2. Collection

33

16
8/19/2020

2. Collection

• Note 2: lưu dữ liệu từ biến vào collection bằng phương


thức save()
> db.Collection_name.save(Variable_name)

o Ví dụ: lưu dữ liệu từ biến book vào collection tên là Books.


1. Khai báo biến book và kiểu dữ liệu của nó
2. Gán giá trị cho các thuộc tính (fieds) của đối tượng book
3. Lưu dữ liệu vào collection bằng lệnh db.Books.save(book)

34

2. Collection

35

17
8/19/2020

2. Collection

36

2. Collection

• Practice 4: Viết lệnh thực hiện các yêu cầu sau


• Tạo database tên là MDB_Course3
• Trong MDB_Course3 tạo collection Users
• Tạo biến user với các thuộc tính user_name, user_password,
user_phone, user_email, user_skills. Biết mỗi user có hơn 1 số
điện thoại và nhiều skills.
• Nhập dữ liệu vào biến user
• Gán dữ liệu từ user vào cho collection Users
• Hiển thị document vừa nhập
• Sử dụng biến user để thêm 2 document mới vào Users
• Hiển thị kết quả
37

18
8/19/2020

3a. Export collection

1. Export ra JSON string


a. Hiển thị danh sách các Collections đang có để lựa chọn collection
muốn export
o Ví dụ, export collection tên là Books

38

3a. Export collection

1. Export ra JSON string


b. Mở chương trình mongoexport

39

19
8/19/2020

3a. Export collection

1. Export ra JSON string


b. Sử dụng chương trình mongoexport để export data:
• Mở cửa sổ cmd mới
• Chuyển tới thư mục bin của MongoDB:

cd "c:\program files\mongodb\server\4.1\bin\”
c:\program files\mongodb\server\4.1\bin>dir

40

3a. Export collection

1. Export ra JSON string

41

20
8/19/2020

3a. Export collection

1. Export ra JSON string


b. Sử dụng chương trình mongoexport để export data (cont.):
• Gọi lệnh export:

mongoexport --db db_name --collection collection_name --out file_name

• hoặc viết tắt:

mongoexport -d db_name -c collection_name -o file_name

• hoặc chỉ rõ đường dẫn:

mongoexport --db db_name --collection collection_name --out


“fullpath\file_name”
42

3a. Export collection

43

21
8/19/2020

3a. Export collection

1. Export ra JSON string


b. Sử dụng chương trình mongoexport để export data (cont.):
• Kiểm tra kết quả:

cd c:\data\
c:\data>dir

44

3a. Export collection

45

22
8/19/2020

3a. Export collection

1. Export ra JSON string


b. Sử dụng chương trình mongoexport để export data (cont.):
• Ví dụ, export Collection5 của db_MongoCourse ra JSON với tên
gọi Collection5.json và lưu ở thư mục c:\data:

46

3a. Export collection

47

23
8/19/2020

3a. Export collection

48

3a. Export collection

2. Export ra file csv


a. Hiển thị danh sách các Collections đang có để lựa chọn collection
muốn export
b. Sử dụng chương trình mongoexport để export data:
• Mở cửa sổ cmd mới
• Chuyển tới thư mục bin của MongoDB:
cd "c:\program files\mongodb\server\4.1\bin\”

49

24
8/19/2020

3a. Export collection

2. Export ra file csv


b. Sử dụng chương trình mongoexport để export data (cont.):
• Gọi lệnh export:

mongoexport --db db_name --collection collection_name --out


file_name.csv --type=csv -f list_of_fields
• hoặc viết tắt:

mongoexport -d db_name -c collection_name -o file_name.csv


--type=csv -f list_of_fields
• hoặc chỉ rõ đường dẫn:

mongoexport --db db_name --collection collection_name --type=csv --out


“fullpath\file_name.csv” -f list_of_fields
50

3a. Export collection

51

25
8/19/2020

3a. Export collection

2. Export ra file csv


b. Sử dụng chương trình mongoexport để export data (cont.):
• Kiểm tra kết quả:

52

3a. Export collection

53

26
8/19/2020

3a. Collection

• Practice 5a: Viết lệnh thực hiện các yêu cầu sau
• Export dữ liệu từ Collection6 của db_MongoCourse ra file
JSON
• File được lưu ở thư mục data\temp ngoài ổ C

• Practice 5b: Viết lệnh thực hiện các yêu cầu sau
• Export dữ liệu từ collection Users của MDB_Course2 (practice
3) ra file csv
• Các trường cần export là tên và mật khẩu
• File được lưu ở thư mục data\temp ngoài ổ C

54 BT 6

3b. Import collection

1. Import từ JSON string


a. Xóa đi Collection muốn import dữ liệu khỏi database
o Ví dụ, xóa collection tên là Books khỏi db_MongoCourse

55

27
8/19/2020

3b. Import collection

1. Import từ JSON string


b. Sử dụng chương trình mongoimport để import data:
• Mở cửa sổ cmd mới
• Chuyển tới thư mục bin của MongoDB:

cd "c:\program files\mongodb\server\4.1\bin\”
c:\program files\mongodb\server\4.1\bin>dir

56

3b. Import collection

1. Import từ JSON string

57

28
8/19/2020

3b. Import collection

1. Import từ JSON string


b. Sử dụng chương trình mongoimport để import data (cont.):
• Gọi lệnh import đầy đủ:

mongoimport --db db_name --collection collection_name --file


“fullpath\file_name”
• hoặc viết tắt:

mongoimport -d db_name -c collection_name --file


“fullpath\file_name”

58

3b. Import collection

59

29
8/19/2020

3b. Import collection

1. Import từ JSON string


b. Sử dụng chương trình mongoimport để import data (cont.):
• Kiểm tra kết quả:

>show collections

60

3b. Import collection

2. Import từ csv file


a. Xóa đi Collection muốn import dữ liệu khỏi database
o Ví dụ, xóa collection tên là Collection1 khỏi db_MongoCourse
b. Sử dụng chương trình mongoimport để import data:
• Mở cửa sổ cmd mới
• Chuyển tới thư mục bin của MongoDB:

cd "c:\program files\mongodb\server\4.1\bin\”

61

30
8/19/2020

3b. Import collection

2. Import từ csv file


b. Sử dụng chương trình mongoimport để import data (cont.):
• Gọi lệnh import đầy đủ:

mongimport --db db_name --collection collection_name --type=csv --file


“fullpath\file_name.csv” --headerline
• hoặc viết tắt:

mongimport -d db_name -c collection_name --type=csv --file


“fullpath\file_name.csv” --headerline

62

3b. Import collection

63

31
8/19/2020

3b. Import collection

2. Import từ csv file


b. Sử dụng chương trình mongoimport để import data (cont.):
• Kiểm tra kết quả:

64

3b. Collection

• Practice 6a: Viết lệnh thực hiện các yêu cầu sau
• Import dữ liệu từ file Collection6.json thu được ở Practice 5a
vào db_MongoCourse.
• Collection được import dữ liệu tên là Collection6

• Practice 6b: Viết lệnh thực hiện các yêu cầu sau
• Import dữ liệu từ file Collection7.csv thu được ở Practice 5b
vào db_MongoCourse.
• Collection được import dữ liệu tên là Collection7

65

32
8/19/2020

4a. Export Database

1. Hiển thị danh sách các database đang có để lựa chọn database
muốn export

show dbs

2. Sử dụng chương trình mongodump để export database:


• Mở cửa sổ cmd mới
• Chuyển tới thư mục bin của MongoDB:
cd "c:\program files\mongodb\server\4.1\bin\”

66

4a. Export Database

1. Import từ JSON string

67

33
8/19/2020

4a. Export Database

• Gọi lệnh export database:


Export bình thường:

>mongodump -d db_name -o “full path”

ex: >mongodump -d db_MongoCourse -o "c:\data\export"

68

4a. Export Database

69

34
8/19/2020

4a. Export Database

70

4a. Export Database

• Gọi lệnh export database:


Export ra thư mục với các file nén:

>mongodump -d db_name -o “full path” --gzip

ex: >mongodump -d db_MongoCourse -o "c:\data\export“ --gzip

71

35
8/19/2020

4a. Export Database

72

4a. Export Database

73

36
8/19/2020

4a. Export Database

• Gọi lệnh export database:


Export ra 1 file nén ở ngay thư mục bin:

>mongdump -d db_name --gzip --archive=filename.gz

ex: >mongodump -d db_MongoCourse –gzip –archive=db_Mongo.1801.gz

74

4a. Export Database

75

37
8/19/2020

4a. Export Database

76

4b. Import Database

• Gọi lệnh import database:


>mongorestore -d db_name “full path”

ex: >mongorestore -d Books "c:\data\export\books"

>mongorestore -d db_name “full path” --gzip

ex: >mongorestore -d Books "c:\data\export\books“ --gzip

>mongorestore -d db_name --gzip --archive=filename.gz

ex: >mongorestore -d Books --gzip --archive=book.1801.gz


77

38
8/19/2020

4b. Import Database

78

Summary

>cls : clear screen


>help : show helps
>exit : exit Mongo Shell Environment
>pwd(): show current directory

• Database:

>use database : create/use


: create/use
database
database
>db : show
: show
currently
currently
database
database
>show dbs : show
: show
available
available
databases
databases
>db.dropDatabase() : delete
: delete
database
database
79

39
8/19/2020

Summary

• Collection

>db.createCollection(name,options) :: create collection


>db.collection.drop() :: delete collectionName
>show collections :: show collections in
currently database.
>db.collection.find() :: show all documents in
collectionName.
>db.collection.find().pretty() :: display finding results in
an easy-to-read format.

80

Summary

• Document
>db.collection.insert() :: insert document(s) into
collectionName.
>db.collection.insertOne() :: insert 1 document into
collectionName.
>db.collection.insertMany([...]) :: insert many documents
into collectionName.
>db.collection.save(variableName) :: save variable value
into collectionName

81

40
8/19/2020

Summary

• Export Collection
>mongoexport –d database –c collection –o path\fileName
export collection to JSON string

>mongoexport –d database –c collection --type=csv –o


path\filename.csv –f list_of_fields
export collection to csv file

82

Summary

• Import Collection
>mongoimport –d database –c collection --file path\fileName
import collection from JSON string

>mongoimport –d database –c collection --type=csv --file


path\filename.csv --headerline
import collection from csv file

83

41
8/19/2020

Summary

• Export Database
>mongodump –d database –o path
export database to path
>mongodump –d database –o path --gzip
export database to zip folder
>mongorestore -d db_name --gzip --archive=filename.gz
export database to zip file

84

Summary

• Import Database
>mongorestore –d database path
Import database from path
>mongorestore –d database path --gzip
Import database from zip folder
>mongorestore –d database --gzip --archive=filename.gz
Import database from zip file

85

42
8/19/2020

Summary

• Practice 7a: Viết lệnh thực hiện các yêu cầu sau
• Tạo database tên là 06_DHCNTTX (X là số hiệu của lớp)
• Tạo collection tên là Members để lưu thông tin cá nhân (Stud_Id,
fullname, skills, favourite)
• Thêm các bản ghi của nhóm mình (3-5 người) vào collection trên
• Export Members ra json string và csv file
• Export 06_DHCNTTX ra 1 file zip
• Practice 7b: Viết lệnh thực hiện các yêu cầu sau:
• Import Members từ json string hoặc csv file của nhóm khác
• Import 06_DHCNTTX từ file zip của nhóm khác
86

5. Datatypes

• Một vài kiểu dữ liệu lưu trữ dữ liệu thường dùng trong MongoDB:
Type Number Alias Notes Descriptions
Double 1 “double” Lưu trữ các giá trị số thực dấu phẩy động
Kiểu dữ liệu phổ biến nhất để lưu trữ
String 2 “string”
data. Định dạng phải là UTF-8
Object 3 “object” Sử dụng cho các embedded documents.
Lưu trữ các mảng hoặc danh sách hoặc
Array 4 “array”
nhiều giá trị vào trong một key.

Binary data 5 “binData” Lưu trữ dữ liệu nhị phân

ObjectId 7 “objectId” Dùng lưu trữ ID của Document.


87

43
8/19/2020

5. Datatypes

• Một vài kiểu dữ liệu lưu trữ dữ liệu thường dùng trong MongoDB:
Type Number Alias Notes Descriptions
Boolean 8 “bool” Lưu trữ một giá trị Boolean (true/false)
lưu trữ date và time hiện tại trong định
Date 9 “date”
dạng UNIX time.
Null 10 “null” Lưu một giá trị Null.

Regular
11 “regex” Lưu trữ biểu thức
Expression

Đánh dấu thời điểm một Document được


Timestamp 17 “timestamp”
sửa đổi hoặc được thêm vào.
New in
Decimal128 19 “decimal” Lưu trữ dữ liệu kiểu thập phân
88 version 3.4.

5. Datatypes

• Một vài kiểu dữ liệu lưu trữ dữ liệu thường dùng trong MongoDB:
Type Number Alias Notes Descriptions
Sử dụng để so sánh một giá trị với các
Min key -1 “minKey”
phần tử BSON thấp nhất
Sử dụng để so sánh một giá trị với các
Max key 127 “maxKey” phần tử BSON cao nhất.

89

44
8/19/2020

$type
• $type chọn các tài liệu trong đó giá trị của trường là một
thể hiện của loại BSON (BSON type) được chỉ định.
• Truy vấn theo data type rất hữu ích khi xử lý dữ liệu phi
cấu trúc cấp cao trong đó các loại dữ liệu không thể dự
đoán được.
• Cú pháp:
{ field: { $type: <BSON type> } }

• hoặc:
{ field: { $type: [ <BSON type1> , <BSON type2>, ... ] } }

90 • Có thể chỉ định số hoặc bí danh (alias) cho loại BSON

$type
• Available Types

Type Number Alias Notes

Double 1 “double”
String 2 “string”
Object 3 “object”
Array 4 “array”
Binary data 5 “binData”
Undefined 6 “undefined” Deprecated.
ObjectId 7 “objectId”
91
Boolean 8 “bool”

45
8/19/2020

$type
Type Number Alias Notes
Date 9 “date”
Null 10 “null”
Regular
11 “regex”
Expression

DBPointer 12 “dbPointer” Deprecated.


JavaScript 13 “javascript”
Symbol 14 “symbol” Deprecated.
JavaScript
15 “javascriptWithScope”
(with scope)
92

$type
Type Number Alias Notes

32-bit integer 16 “int”

Timestamp 17 “timestamp”

64-bit integer 18 “long”

Decimal128 19 “decimal” New in version 3.4.

Min key -1 “minKey”

Max key 127 “maxKey”

93

46
8/19/2020

$type

• Trường hợp $type trả về kiểu của đối số:

Example Results
{ $type: "a" } "string"
{ $type: /a/ } "regex"
{ $type: 1 } "double"
{ $type: NumberLong(627) } "long"
{ $type: { x: 1 } } "object"
{ $type: [ [ 1, 2, 3 ] ] } "array"

94

Min key – Max key

• MinKey và MaxKey được dùng trong các hoạt động so


sánh và tồn tại chủ yếu để sử dụng nội bộ.

• Truy vấn cho minKey hay maxKey với $type sẽ chỉ trả
về các trường (fields) mà khớp với giá trị của MinKey
hoặc MaxKey

95

47
8/19/2020

Min key – Max key

• Gỉa sử data collection có 2 documents với minKey và


maxKey:
{ "_id" : 1, x : { "$minKey" : 1 } }
{ "_id" : 2, y : { "$maxKey" : 1 } }

• Truy vấn sau trả về document có _id : 1


db.data.find( { x: { $type: "minKey" } } )

• Truy vấn sau trả về document có _id : 2


db.data.find( { y: { $type: "maxKey" } } )

96

Querying by Data Type

• addressBook collection chứa các address và zipcode,


trong đó zipCode gồm các giá trị ở dạng string, int,
double, long:
db.addressBook.insertMany(
[
{ "_id" : 1, address : "2030 Martian Way", zipCode : "90698345" },
{ "_id" : 2, address: "156 Lunar Place", zipCode : 43339374 },
{ "_id" : 3, address : "2324 Pluto Place", zipCode: NumberLong(3921412) },
{ "_id" : 4, address : "55 Saturn Ring" , zipCode : NumberInt(88602117) }
]
)
97

48
8/19/2020

Querying by Data Type

• Các truy vấn sau trả về tất cả documents có zipCode ở


dạng chuỗi BSON (BSON type string):
db.addressBook.find( { "zipCode" : { $type : 2 } } );
db.addressBook.find( { "zipCode" : { $type : "string" } } );

• Kết quả truy vấn:


{ "_id" : 1, "address" : "2030 Martian Way", "zipCode" : "90698345" }

98

Querying by Data Type

• Các truy vấn sau trả về tất cả documents có zipCode ở


dạng double (BSON type double):
db.addressBook.find( { "zipCode" : { $type : 1 } } )
db.addressBook.find( { "zipCode" : { $type : "double" } } )

• Kết quả truy vấn:


{ "_id" : 2, "address" : "156 Lunar Place", "zip" : 43339374 }

99

49
8/19/2020

Querying by Data Type

• Các truy vấn sau sử dụng number alias để trả về tất cả


documents có zipCode ở dạng double, int hoặc long
db.addressBook.find( { "zipCode" : { $type : "number" } } )

• Kết quả truy vấn:


{ "_id" : 2, address : "156 Lunar Place", zipCode : 43339374 }
{ "_id" : 3, address : "2324 Pluto Place", zipCode: NumberLong(3921412) }
{ "_id" : 4, address : "55 Saturn Ring" , zipCode : 88602117 }

100

Querying by Multiple Data Type

• grades collection chứa các name và averages, trong đó


classAverage gồm các giá trị ở dạng string, int, double:

db.grades.insertMany(
[
{ "_id" : 1, name : "Alice King" , classAverage : 87.333333333333333 },
{ "_id" : 2, name : "Bob Jenkins", classAverage : "83.52" },
{ "_id" : 3, name : "Cathy Hart", classAverage: "94.06" },
{ "_id" : 4, name : "Drew Williams" , classAverage : 93 }
]
)
101

50
8/19/2020

Querying by Multiple Data Type

• Các truy vấn sau trả về tất cả documents có averages ở


dạng string hoặc double. Truy vấn đầu sử dụng
numeric aliases còn truy vấn sau sử dụng string aliases.
db.grades.find( { "classAverage" : { $type : [ 2 , 1 ] } } );
db.grades.find( { "classAverage" : { $type : [ "string" , "double" ] } } );

• Kết quả truy vấn:


{ "_id" : 1, name : "Alice King" , classAverage : 87.333333333333333 }
{ "_id" : 2, name : "Bob Jenkins", classAverage : "83.52" }
{ "_id" : 3, name : "Cathy Hart", classAverage: "94.06" }

102

Querying by Multiple Data Type

• test2019 collection sử dụng minKey cho bất kỳ người


nào dưới 18 tuổi và maxKey cho bất kỳ ai trên 60 tuổi:
{ "_id" : 1, "name" : "An", "age" : 18 }
{ "_id" : 3, "name" : "Trang", "age" : { "$minKey" : 1 } }
{ "_id" : 4, "name" : "Hung", "age" : { "$maxKey" : 1 } }
{ "_id" : 5, "name" : "Mai", "age" : 20 }
{ "_id" : 6, "name" : "Vi", "age" : 45 }
{ "_id" : 7, "name" : "My", "age" : { "$minKey" : 1 } }
{ "_id" : 8, "name" : "Quang", "age" : { "$maxKey" : 1 } }
{ "_id" : 2, "name" : "Binh", "age" : 39 }
103

51
8/19/2020

Querying by Multiple Data Type

• Các truy vấn sau trả về tất cả những người mà có trường


age chứa minKey

db.test2019.find( { “age" : { $type : "minKey" } } )

• Kết quả truy vấn:

{ "_id" : 3, "name" : "Trang", "age" : { "$minKey" : 1 } }


{ "_id" : 7, "name" : "My", "age" : { "$minKey" : 1 } }
104

Querying by Multiple Data Type

• Các truy vấn sau trả về tất cả những người mà có trường


age chứa maxKey

db.test2019.find( { “age" : { $type : "maxKey" } })

• Kết quả truy vấn:

{ "_id" : 4, "name" : "Hung", "age" : { "$maxKey" : 1 } }


{ "_id" : 8, "name" : "Quang", "age" : { "$maxKey" : 1 } }
105

52
8/19/2020

Querying by Multiple Data Type


{
"_id": 1, • Restaurant collection sử dụng minKey cho bất kỳ lớp nào
"address": { "building":
mà điểm"230", "coord":
không đạt:[ -73.996089, 40.675018 ],
"street": "Huntington St", "zipcode": "11231" },
"borough": "Brooklyn",
"cuisine": "Bakery",
"grades": [
{ "date": new Date(1393804800000), "grade": "C", "score": 15 },
{ "date": new Date(1378857600000), "grade": "C", "score": 16 },
{ "date": new Date(1358985600000), "grade": MinKey(), "score": 30 },
{ "date": new Date(1322006400000), "grade": "C", "score": 15 }
],
"name": "Dirty Dan's Donuts",
"restaurant_id": "30075445"
106
}

Querying by Multiple Data Type


{
"_id": 2, • Và maxKey cho bất kỳ lớp nào là lớp thi qua cao nhất:
"address": {"building": "1166", "coord": [ -73.955184, 40.738589 ],
"street": "Manhattan Ave", "zipcode": "11222" },
"borough": "Brooklyn",
"cuisine": "Bakery",
"grades": [
{ "date": new Date(1393804800000), "grade": MaxKey(), "score": 2 },
{ "date": new Date(1378857600000), "grade": "B", "score": 6 },
{ "date": new Date(1358985600000), "grade": MaxKey(), "score": 3 },
{ "date": new Date(1322006400000), "grade": "B", "score": 5 }
],
"name": "Dainty Daisey's Donuts",
"restaurant_id": "30075449"
107
}

53
8/19/2020

Querying by Multiple Data Type

• Các truy vấn sau trả về tất cả restaurant mà có


grades.grade field chứa minKey

db.restaurants.find(
{ "grades.grade" : { $type : "minKey" } }
)

• Kết quả truy vấn:

108

Querying by Multiple Data Type


{
"_id" : 1,
"address" : { "building" : "230", "coord" : [ -73.996089, 40.675018 ],
"street" : "Huntington St", "zipcode" : "11231" },
"borough" : "Brooklyn",
"cuisine" : "Bakery",
"grades" : [
{ "date" : ISODate("2014-03-03T00:00:00Z"), "grade" : "C", "score" : 15 },
{ "date" : ISODate("2013-09-11T00:00:00Z"), "grade" : "C", "score" : 16 },
{ "date" : ISODate("2013-01-24T00:00:00Z"), "grade" : { "$minKey" : 1 }, "score" : 30 },
{ "date" : ISODate("2011-11-23T00:00:00Z"), "grade" : "C", "score" : 15 }
],
"name" : "Dirty Dan's Donuts",
"restaurant_id" : "30075445"
}109

54
8/19/2020

Querying by Multiple Data Type

• Các truy vấn sau trả về tất cả restaurant mà có


grades.grade field chứa maxKey

db.restaurants.find(
{ "grades.grade" : { $type : "maxKey" } }
)

• Kết quả truy vấn:

110

Querying by Multiple Data Type


{
"_id" : 2,
"address" : {"building" : "1166", "coord" : [ -73.955184, 40.738589 ],
"street" : "Manhattan Ave", "zipcode" : "11222" },
"borough" : "Brooklyn",
"cuisine" : "Bakery",
"grades" : [
{ "date" : ISODate("2014-03-03T00:00:00Z"), "grade" : { "$maxKey" : 1 }, "score" : 2 },
{ "date" : ISODate("2013-09-11T00:00:00Z"), "grade" : "B", "score" : 6 },
{ "date" : ISODate("2013-01-24T00:00:00Z"), "grade" : { "$maxKey" : 1 }, "score" : 3 },
{ "date" : ISODate("2011-11-23T00:00:00Z"), "grade" : "B", "score" : 5 }
],
"name" : "Dainty Daisey's Donuts",
"restaurant_id" : "30075449"
}111

55
8/19/2020

{
"_id": 1, Querying by Array Type
"readings": [25, 23, [ "Warn: High Temp!", 55 ],
[ "ERROR: SYSTEM
• SensorReading SHUTDOWN!",
collection 66 ] ]
chứa các documents sau:
},
{
"_id": 2, "readings": [ 25, 25, 24, 23 ]
},
{
"_id": 3, "readings": [ 22, 24, [] ]
},
{
"_id": 4, "readings": []
},
{
"_id": 5, "readings": 24
112
}

Querying by Multiple Data Type

• Các truy vấn sau trả về các document mà readings field


là một mảng, empty hoặc không empty

db.SensorReading.find( { "readings" : { $type: "array" } } )

• Kết quả truy vấn:

113

56
8/19/2020

{
"_id": 1, Querying by Multiple Data Type
"readings": [ 25, 23, [ "Warn: High Temp!", 55 ],
[ "ERROR: SYSTEM SHUTDOWN!", 66 ] ]
},
{
"_id": 2,
"readings": [ 25, 25, 24, 23 ]
},
{
"_id": 3,
"readings": [ 22, 24, [] ]
},
{
"_id": 4, "readings": []
}
114

Summary

• Practice 8: Viết lệnh thực hiện các yêu cầu sau


• Trong collection Members sau, liệt kê các thành viên (member)
có nhiều hơn 1 tên gọi hoặc tên gọi là 1 số

{ "_id" : 1, "name" : "An", "age" : 18 }


{ "_id" : 3, "name" : 114, "age" : { "$minKey" : 1 } }
{ "_id" : 4, "name" : ["Hung“, ”Quang”], "age" : { "$maxKey" : 1 } }
{ "_id" : 5, "name" : "Mai", "age" : 20 }
{ "_id" : 6, "name" : ["Vi“, “Van”], "age" : 45 }
{ "_id" : 7, "name" : "My", "age" : { "$minKey" : 1 } }
{ "_id" : 8, "name" : 113, "age" : { "$maxKey" : 1 } }
{ "_id" : 2, "name" : "Binh", "age" : 39 }
115

57
8/19/2020

DEMO

116

58

You might also like