Tài liệu mongodb được lưu trữ như thế nào?

MongoDB is a cross-platform, document oriented database that provides, high performance, high availability, and easy scalability. MongoDB works on concept of collection and document

Show

Database

Cơ sở dữ liệu là một thùng chứa vật lý cho các bộ sưu tập. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases

Bộ sưu tập

Bộ sưu tập là một nhóm các tài liệu MongoDB. It is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose

Document

A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema means that documents in the same collection do not need to have the same set of fields or structure, and common fields in a collection's documents may hold different types of data

The following table shows the relationship of RDBMS terminology with MongoDB

RDBMSMongoDBDatabaseDatabaseTableCollectionTuple/RowDocumentcolumnFieldTable JoinEmbedded DocumentsPrimary KeyPrimary Key (Default key _id provided by mongodb itself)Database Server and ClientMysqld/Oraclemongodmysql/sqlplusmongo

Sample Document

Following example shows the document structure of a blog site, which is simply a comma separated key value pair

{
   _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, 
   comments: [	
      {
         user:'user1',
         message: 'My first comment',
         dateCreated: new Date(2011,1,20,2,15),
         like: 0 
      },
      {
         user:'user2',
         message: 'My second comments',
         dateCreated: new Date(2011,1,25,7,45),
         like: 5
      }
   ]
}

_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You can provide _id while inserting the document. If you don’t provide then MongoDB provides a unique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3 bytes for machine id, next 2 bytes for process id of MongoDB server and remaining 3 bytes are simple incremental VALUE

Any relational database has a typical schema design that shows number of tables and the relationship between these tables. While in MongoDB, there is no concept of relationship

Advantages of MongoDB over RDBMS

  • Schema less − MongoDB is a document database in which one collection holds different documents. Number of fields, content and size of the document can differ from one document to another

  • Structure of a single object is clear

  • No complex joins

  • Deep query-ability. MongoDB supports dynamic queries on documents using a document-based query language that's nearly as powerful as SQL

  • Tuning

  • Ease of scale-out − MongoDB is easy to scale

  • Conversion/mapping of application objects to database objects not needed

  • Uses internal memory for storing the (windowed) working set, enabling faster access of data

Why Use MongoDB?

  • Lưu trữ hướng tài liệu - Dữ liệu được lưu trữ ở dạng tài liệu kiểu JSON

  • Lập chỉ mục trên bất kỳ thuộc tính nào

  • Sao chép và tính sẵn sàng cao

  • Tự động phân mảnh

  • truy vấn phong phú

  • Cập nhật tại chỗ nhanh chóng

  • Hỗ trợ chuyên nghiệp bởi MongoDB

Sử dụng MongoDB ở đâu?

  • Dữ liệu lớn
  • Quản lý và phân phối nội dung
  • Cơ sở hạ tầng di động và xã hội
  • Quản lý dữ liệu người dùng
  • Trung tâm dữ liệu

Bây giờ chúng ta hãy xem cách cài đặt MongoDB trên Windows

Cài đặt MongoDB trên Windows

Để cài đặt MongoDB trên Windows, trước tiên hãy tải xuống bản phát hành MongoDB mới nhất từ ​​https. //www. mongodb. tổ chức/tải xuống. Đảm bảo bạn có phiên bản MongoDB chính xác tùy thuộc vào phiên bản Windows của bạn. Để có phiên bản Windows của bạn, hãy mở dấu nhắc lệnh và thực hiện lệnh sau

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>

Phiên bản 32-bit của MongoDB chỉ hỗ trợ cơ sở dữ liệu nhỏ hơn 2GB và chỉ phù hợp cho mục đích thử nghiệm và đánh giá

Bây giờ hãy giải nén tệp đã tải xuống của bạn vào c. \ ổ đĩa hoặc bất kỳ vị trí nào khác. Make sure the name of the extracted folder is mongodb-win32-i386-[version] or mongodb-win32-x86_64-[version]. Đây [phiên bản] là phiên bản tải xuống MongoDB

Tiếp theo, mở dấu nhắc lệnh và chạy lệnh sau

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>

Trong trường hợp bạn đã trích xuất MongoDB ở một vị trí khác, thì hãy đi đến đường dẫn đó bằng cách sử dụng lệnh cd FOLDER/DIR và bây giờ hãy chạy quy trình đã cho ở trên

MongoDB yêu cầu một thư mục dữ liệu để lưu trữ các tệp của nó. Vị trí mặc định cho thư mục dữ liệu MongoDB là c. \data\db. Vì vậy, bạn cần tạo thư mục này bằng Command Prompt. Thực hiện chuỗi lệnh sau

C:\>md data
C:\md data\db

Nếu bạn phải cài đặt MongoDB ở một vị trí khác, thì bạn cần chỉ định một đường dẫn thay thế cho \data\db bằng cách đặt đường dẫn dbpath trong mongod. người cũ. Đối với cùng, đưa ra các lệnh sau

Trong dấu nhắc lệnh, điều hướng đến thư mục bin có trong thư mục cài đặt MongoDB. Giả sử thư mục cài đặt của tôi là D. \thiết lập\mongodb

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 

Điều này sẽ hiển thị thông báo chờ kết nối trên đầu ra của bàn điều khiển, điều này cho biết rằng mongod. exe đang chạy thành công

Bây giờ để chạy MongoDB, bạn cần mở một dấu nhắc lệnh khác và đưa ra lệnh sau

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>

Điều này sẽ cho thấy MongoDB đã được cài đặt và chạy thành công. Lần tới khi bạn chạy MongoDB, bạn chỉ cần đưa ra các lệnh

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
D:\set up\mongodb\bin>mongo.exe

Cài đặt MongoDB trên Ubuntu

Chạy lệnh sau để nhập khóa GPG công khai MongoDB -

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

Tạo một /etc/apt/sources. danh sách. d/mongodb. liệt kê tập tin bằng cách sử dụng lệnh sau

________số 8_______

Bây giờ hãy đưa ra lệnh sau để cập nhật kho lưu trữ -

sudo apt-get update

Tiếp theo cài đặt MongoDB bằng cách sử dụng lệnh sau -

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
0

Trong cài đặt trên, 2. 2. 3 hiện đang được phát hành phiên bản MongoDB. Đảm bảo luôn cài đặt phiên bản mới nhất. Bây giờ MongoDB đã được cài đặt thành công

Bắt đầu MongoDB

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
1

Dừng MongoDB

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
2

Khởi động lại MongoDB

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
3

Để sử dụng MongoDB, hãy chạy lệnh sau

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
4

Điều này sẽ kết nối bạn với phiên bản MongoDB đang chạy

Trợ giúp MongoDB

Để có danh sách các lệnh, hãy nhập db. trợ giúp () trong ứng dụng khách MongoDB. Điều này sẽ cung cấp cho bạn một danh sách các lệnh như trong ảnh chụp màn hình sau

Tài liệu mongodb được lưu trữ như thế nào?

Thống kê MongoDB

Để lấy số liệu thống kê về máy chủ MongoDB, hãy nhập lệnh db. stats() trong ứng dụng khách MongoDB. Điều này sẽ hiển thị tên cơ sở dữ liệu, số lượng bộ sưu tập và tài liệu trong cơ sở dữ liệu. Đầu ra của lệnh được hiển thị trong ảnh chụp màn hình sau

Tài liệu mongodb được lưu trữ như thế nào?

Dữ liệu trong MongoDB có lược đồ linh hoạt. tài liệu trong cùng một bộ sưu tập. Chúng không cần phải có cùng một bộ trường hoặc cấu trúc và các trường chung trong tài liệu của bộ sưu tập có thể chứa các loại dữ liệu khác nhau

Một số lưu ý khi thiết kế Schema trong MongoDB

  • Thiết kế lược đồ của bạn theo yêu cầu của người dùng

  • Kết hợp các đối tượng vào một tài liệu nếu bạn sẽ sử dụng chúng cùng nhau. Mặt khác, hãy tách chúng ra (nhưng đảm bảo rằng không cần tham gia)

  • Sao chép dữ liệu (nhưng có giới hạn) vì dung lượng đĩa rẻ so với thời gian tính toán

  • Thực hiện tham gia trong khi viết, không phải khi đọc

  • Tối ưu hóa lược đồ của bạn cho hầu hết các trường hợp sử dụng thường xuyên

  • Thực hiện tổng hợp phức tạp trong lược đồ

Thí dụ

Giả sử một khách hàng cần thiết kế cơ sở dữ liệu cho blog/trang web của mình và xem sự khác biệt giữa thiết kế lược đồ RDBMS và MongoDB. Website có các yêu cầu sau

  • Mỗi bài đăng có tiêu đề, mô tả và url duy nhất
  • Mỗi bài đăng có thể có một hoặc nhiều thẻ
  • Every post has the name of its publisher and total number of likes
  • Mỗi bài đăng đều có nhận xét của người dùng cùng với tên, tin nhắn, thời gian dữ liệu và lượt thích của họ
  • Trên mỗi bài đăng, có thể có 0 hoặc nhiều bình luận

Trong lược đồ RDBMS, thiết kế cho các yêu cầu trên sẽ có tối thiểu ba bảng

Tài liệu mongodb được lưu trữ như thế nào?

Trong lược đồ MongoDB, thiết kế sẽ có một bài đăng bộ sưu tập và cấu trúc sau -

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
5

Vì vậy, trong khi hiển thị dữ liệu, trong RDBMS, bạn cần nối ba bảng và trong MongoDB, dữ liệu sẽ chỉ được hiển thị từ một bộ sưu tập

Trong chương này, chúng ta sẽ xem cách tạo cơ sở dữ liệu trong MongoDB

Lệnh sử dụng

MongoDB sử dụng DATABASE_NAME được sử dụng để tạo cơ sở dữ liệu. Lệnh sẽ tạo cơ sở dữ liệu mới nếu nó chưa tồn tại, ngược lại nó sẽ trả về cơ sở dữ liệu hiện có

cú pháp

Cú pháp cơ bản của câu lệnh use DATABASE như sau -

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
6

Thí dụ

Nếu bạn muốn sử dụng cơ sở dữ liệu có tên , thì hãy sử dụng câu lệnh DATABASE như sau -

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
7

Để kiểm tra cơ sở dữ liệu hiện được chọn của bạn, hãy sử dụng lệnh db

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
8

Nếu bạn muốn kiểm tra danh sách cơ sở dữ liệu của mình, hãy sử dụng lệnh show dbs

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
9

Cơ sở dữ liệu đã tạo của bạn (mydb) không có trong danh sách. Để hiển thị cơ sở dữ liệu, bạn cần chèn ít nhất một tài liệu vào đó

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>
0

Trong cơ sở dữ liệu mặc định của MongoDB là test. Nếu bạn không tạo bất kỳ cơ sở dữ liệu nào, thì các bộ sưu tập sẽ được lưu trữ trong cơ sở dữ liệu thử nghiệm

Trong chương này, chúng ta sẽ xem cách xóa cơ sở dữ liệu bằng lệnh MongoDB

Phương thức dropDatabase()

cơ sở dữ liệu MongoDB. dropDatabase() được sử dụng để loại bỏ cơ sở dữ liệu hiện có

cú pháp

Cú pháp cơ bản của lệnh dropDatabase() như sau -

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>
1

Thao tác này sẽ xóa cơ sở dữ liệu đã chọn. Nếu bạn chưa chọn bất kỳ cơ sở dữ liệu nào, nó sẽ xóa cơ sở dữ liệu 'thử nghiệm' mặc định

Thí dụ

Đầu tiên, kiểm tra danh sách các cơ sở dữ liệu có sẵn bằng cách sử dụng lệnh, show dbs

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>
2

Nếu bạn muốn xóa cơ sở dữ liệu mới, lệnh dropDatabase() sẽ như sau:

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>
3

Bây giờ hãy kiểm tra danh sách cơ sở dữ liệu

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>
4

Trong chương này, chúng ta sẽ xem cách tạo một bộ sưu tập bằng MongoDB

Phương thức createCollection()

cơ sở dữ liệu MongoDB. createCollection(name, options) được sử dụng để tạo bộ sưu tập

cú pháp

Cú pháp cơ bản của lệnh createCollection() như sau -

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>
5

Trong lệnh, tên là tên của bộ sưu tập sẽ được tạo. Tùy chọn là một tài liệu và được sử dụng để chỉ định cấu hình của bộ sưu tập

Tham sốTypeDescriptionNameStringName của bộ sưu tập sẽ được tạoOptionsDocument(Tùy chọn) Chỉ định các tùy chọn về kích thước bộ nhớ và lập chỉ mục

Tham số tùy chọn là tùy chọn, vì vậy bạn chỉ cần chỉ định tên của bộ sưu tập. Sau đây là danh sách các tùy chọn bạn có thể sử dụng –

FieldTypeDescriptioncappedBoolean(Tùy chọn) Nếu đúng, bật bộ sưu tập giới hạn. Bộ sưu tập được giới hạn là bộ sưu tập có kích thước cố định tự động ghi đè lên các mục nhập cũ nhất khi đạt đến kích thước tối đa. Nếu bạn chỉ định đúng, bạn cũng cần chỉ định tham số kích thước. autoIndexIdBoolean(Tùy chọn) Nếu đúng, tự động tạo chỉ mục trên trường _id. s Giá trị mặc định là sai. sizenumber(Tùy chọn) Chỉ định kích thước tối đa tính bằng byte cho bộ sưu tập giới hạn. Nếu giới hạn là đúng, thì bạn cũng cần chỉ định trường này. maxnumber(Tùy chọn) Chỉ định số lượng tài liệu tối đa được phép trong bộ sưu tập giới hạn

Trong khi chèn tài liệu, MongoDB trước tiên kiểm tra trường kích thước của bộ sưu tập giới hạn, sau đó kiểm tra trường tối đa

ví dụ

Cú pháp cơ bản của phương thức createCollection() không có tùy chọn như sau:

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>
6

Bạn có thể kiểm tra bộ sưu tập đã tạo bằng cách sử dụng lệnh show collections

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>
7

Ví dụ sau đây cho thấy cú pháp của phương thức createCollection() với một số tùy chọn quan trọng –

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>
8

Trong MongoDB, bạn không cần tạo bộ sưu tập. MongoDB tự động tạo bộ sưu tập khi bạn chèn một số tài liệu

C:\>move mongodb-win64-* mongodb
   1 dir(s) moved.
C:\>
9

Trong chương này, chúng ta sẽ xem cách loại bỏ một bộ sưu tập bằng MongoDB

Phương thức drop()

Cơ sở dữ liệu của MongoDB. thu thập. drop() được sử dụng để loại bỏ một bộ sưu tập khỏi cơ sở dữ liệu

cú pháp

Cú pháp cơ bản của lệnh drop() như sau -

C:\>md data
C:\md data\db
0

Thí dụ

Trước tiên, hãy kiểm tra các bộ sưu tập có sẵn trong cơ sở dữ liệu của bạn mydb

C:\>md data
C:\md data\db
1

Bây giờ thả bộ sưu tập với tên mycollection

C:\>md data
C:\md data\db
2

Kiểm tra lại danh sách các bộ sưu tập vào cơ sở dữ liệu

C:\>md data
C:\md data\db
3

Phương thức drop() sẽ trả về true, nếu bộ sưu tập đã chọn được hủy thành công, nếu không, nó sẽ trả về false

MongoDB hỗ trợ nhiều kiểu dữ liệu. Một số trong số họ là -

  • Chuỗi - Đây là kiểu dữ liệu được sử dụng phổ biến nhất để lưu trữ dữ liệu. Chuỗi trong MongoDB phải hợp lệ UTF-8

  • Số nguyên - Loại này được sử dụng để lưu trữ một giá trị số. Số nguyên có thể là 32 bit hoặc 64 bit tùy thuộc vào máy chủ của bạn

  • Boolean - Loại này được sử dụng để lưu trữ giá trị boolean (true/false)

  • Double - Loại này được sử dụng để lưu trữ các giá trị dấu chấm động

  • Phím tối thiểu/tối đa - Loại này được sử dụng để so sánh một giá trị với các phần tử BSON thấp nhất và cao nhất

  • Mảng - Loại này được sử dụng để lưu trữ mảng hoặc danh sách hoặc nhiều giá trị vào một khóa

  • Dấu thời gian − ctimestamp. Điều này có thể hữu ích để ghi lại khi một tài liệu đã được sửa đổi hoặc thêm vào

  • Đối tượng - Kiểu dữ liệu này được sử dụng cho các tài liệu nhúng

  • Null - Loại này được sử dụng để lưu trữ giá trị Null

  • Biểu tượng - Kiểu dữ liệu này được sử dụng giống hệt với một chuỗi;

  • Ngày - Kiểu dữ liệu này được sử dụng để lưu trữ ngày hoặc giờ hiện tại ở định dạng thời gian UNIX. Bạn có thể chỉ định thời gian ngày của riêng mình bằng cách tạo đối tượng Ngày và chuyển ngày, tháng, năm vào đó

  • ID đối tượng - Kiểu dữ liệu này được sử dụng để lưu trữ ID của tài liệu

  • Dữ liệu nhị phân - Kiểu dữ liệu này được sử dụng để lưu trữ dữ liệu nhị phân

  • Mã - Kiểu dữ liệu này được sử dụng để lưu mã JavaScript vào tài liệu

  • Biểu thức chính quy - Kiểu dữ liệu này được sử dụng để lưu trữ biểu thức chính quy

Trong chương này, chúng ta sẽ tìm hiểu cách chèn tài liệu vào bộ sưu tập MongoDB

Phương thức chèn()

Để chèn dữ liệu vào bộ sưu tập MongoDB, bạn cần sử dụng phương thức insert() hoặc save() của MongoDB

cú pháp

Cú pháp cơ bản của lệnh insert() như sau -

C:\>md data
C:\md data\db
4

Thí dụ

C:\>md data
C:\md data\db
5

Ở đây mycol là tên bộ sưu tập của chúng tôi, như được tạo trong chương trước. Nếu bộ sưu tập không tồn tại trong cơ sở dữ liệu, thì MongoDB sẽ tạo bộ sưu tập này và sau đó chèn một tài liệu vào đó

Trong tài liệu được chèn vào, nếu chúng ta không chỉ định tham số _id thì MongoDB sẽ gán một ObjectId duy nhất cho tài liệu này

_id là số thập lục phân 12 byte duy nhất cho mọi tài liệu trong bộ sưu tập. 12 byte được chia như sau -

C:\>md data
C:\md data\db
6

Để chèn nhiều tài liệu trong một truy vấn, bạn có thể truyền một mảng tài liệu vào lệnh insert()

Thí dụ

C:\>md data
C:\md data\db
7

Để chèn tài liệu, bạn có thể sử dụng db. bưu kiện. lưu (tài liệu) cũng. Nếu bạn không chỉ định _id trong tài liệu thì phương thức save() sẽ hoạt động giống như phương thức insert(). Nếu bạn chỉ định _id thì nó sẽ thay thế toàn bộ dữ liệu của tài liệu chứa _id như được chỉ định trong phương thức save()

Trong chương này, chúng ta sẽ tìm hiểu cách truy vấn tài liệu từ bộ sưu tập MongoDB

Phương thức find()

Để truy vấn dữ liệu từ bộ sưu tập MongoDB, bạn cần sử dụng phương thức find() của MongoDB

cú pháp

Cú pháp cơ bản của phương thức find() như sau -

C:\>md data
C:\md data\db
8

phương thức find() sẽ hiển thị tất cả các tài liệu theo cách không có cấu trúc

Phương thức xinh()

Để hiển thị kết quả theo cách đã định dạng, bạn có thể sử dụng phương thức pretty()

cú pháp

C:\>md data
C:\md data\db
9

Thí dụ

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
0

Ngoài phương thức find(), còn có phương thức findOne() chỉ trả về một tài liệu

RDBMS Where Mệnh đề tương đương trong MongoDB

Để truy vấn tài liệu trên cơ sở một số điều kiện, bạn có thể sử dụng các thao tác sau

OperationSyntaxExampleRDBMS EquivalentEquality{:}db.mycol.find({"by":"tutorials point"}).pretty()where by = 'tutorials point'Less Than{:{$lt:}}db.mycol.find({"likes":{$lt:50}}).pretty()where likes < 50Less Than Equals{:{$lte:}}db.mycol.find({"likes":{$lte:50}}).pretty()where likes <= 50Greater Than{:{$gt:}}db.mycol.find({"likes":{$gt:50}}).pretty()where likes > 50Greater Than Equals{:{$gte:}}db.mycol.find({"likes":{$gte:50}}).pretty()where likes >= 50Not Equals{:{$ne:}}db.mycol.find({"likes":{$ne:50}}).pretty()where likes != 50

VÀ trong MongoDB

cú pháp

Trong phương thức find(), nếu bạn chuyển nhiều khóa bằng cách tách chúng bằng ',' thì MongoDB sẽ coi đó là điều kiện AND. Sau đây là cú pháp cơ bản của AND −

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
1

Thí dụ

Ví dụ sau sẽ hiển thị tất cả các hướng dẫn được viết bởi 'điểm hướng dẫn' và có tiêu đề là 'Tổng quan về MongoDB'

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
2

Đối với ví dụ đã cho ở trên, mệnh đề where tương đương sẽ là ' where by = 'điểm hướng dẫn' VÀ title = 'Tổng quan về MongoDB''. Bạn có thể chuyển bất kỳ số lượng cặp khóa, giá trị nào trong mệnh đề find

HOẶC trong MongoDB

cú pháp

Để truy vấn tài liệu dựa trên điều kiện OR, bạn cần sử dụng từ khóa $or. Sau đây là cú pháp cơ bản của OR −

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
3

Thí dụ

Ví dụ sau sẽ hiển thị tất cả các hướng dẫn được viết bởi 'điểm hướng dẫn' hoặc có tiêu đề là 'Tổng quan về MongoDB'

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
4

Sử dụng AND và OR cùng nhau

Thí dụ

Ví dụ sau sẽ hiển thị các tài liệu có lượt thích lớn hơn 10 và có tiêu đề là 'Tổng quan về MongoDB' hoặc theo 'điểm hướng dẫn'. SQL tương đương mệnh đề where là 'where likes>10 AND (by = 'tutorials point' OR title = 'MongoDB Overview')'

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
5

Các phương thức update() và save() của MongoDB được sử dụng để cập nhật tài liệu vào một bộ sưu tập. Phương thức update() cập nhật các giá trị trong tài liệu hiện có trong khi phương thức save() thay thế tài liệu hiện có bằng tài liệu được truyền trong phương thức save()

Phương thức cập nhật MongoDB()

Phương thức update() cập nhật các giá trị trong tài liệu hiện có

cú pháp

Cú pháp cơ bản của phương thức update() như sau -

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
6

Thí dụ

Hãy xem xét bộ sưu tập mycol có dữ liệu sau

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
7

Ví dụ sau sẽ đặt tiêu đề mới 'Hướng dẫn MongoDB mới' cho các tài liệu có tiêu đề là 'Tổng quan về MongoDB'

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
8

Theo mặc định, MongoDB sẽ chỉ cập nhật một tài liệu duy nhất. Để cập nhật nhiều tài liệu, bạn cần đặt tham số 'multi' thành true

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
9

Phương thức Lưu () MongoDB

Phương thức save() thay thế tài liệu hiện có bằng tài liệu mới được truyền vào phương thức save()

cú pháp

Cú pháp cơ bản của phương thức save() trong MongoDB được hiển thị bên dưới -

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
0

Thí dụ

Ví dụ sau sẽ thay thế tài liệu bằng _id '5983548781331adf45ec5'

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
1

Trong chương này, chúng ta sẽ tìm hiểu cách xóa một tài liệu bằng MongoDB

Phương thức loại bỏ ()

Phương thức remove() của MongoDB được sử dụng để xóa tài liệu khỏi bộ sưu tập. phương thức remove() chấp nhận hai tham số. Một là tiêu chí xóa và thứ hai là cờ justOne

  • tiêu chí xóa − (Tùy chọn) tiêu chí xóa theo tài liệu sẽ bị xóa

  • justOne − (Tùy chọn) nếu được đặt thành true hoặc 1, sau đó chỉ xóa một tài liệu

cú pháp

Cú pháp cơ bản của phương thức remove() như sau -

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
2

Thí dụ

Hãy xem xét bộ sưu tập mycol có dữ liệu sau

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
7

Ví dụ sau sẽ xóa tất cả các tài liệu có tiêu đề là 'Tổng quan về MongoDB'

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
4

Chỉ xóa một

Nếu có nhiều bản ghi và bạn chỉ muốn xóa bản ghi đầu tiên, thì hãy đặt tham số justOne trong phương thức remove()

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
5

Xóa tất cả tài liệu

Nếu bạn không chỉ định tiêu chí xóa thì MongoDB sẽ xóa toàn bộ tài liệu khỏi bộ sưu tập. Điều này tương đương với lệnh truncate của SQL

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
6

Trong MongoDB, phép chiếu có nghĩa là chỉ chọn dữ liệu cần thiết thay vì chọn toàn bộ dữ liệu của tài liệu. Nếu tài liệu có 5 trường và bạn chỉ cần hiển thị 3 trường thì chỉ chọn 3 trường trong số đó

Phương thức find()

Phương thức find() của MongoDB, được giải thích trong MongoDB Query Document chấp nhận tham số tùy chọn thứ hai là danh sách các trường mà bạn muốn truy xuất. Trong MongoDB, khi bạn thực thi phương thức find() thì nó sẽ hiển thị tất cả các trường của tài liệu. Để hạn chế điều này, bạn cần thiết lập danh sách các trường có giá trị 1 hoặc 0. 1 được sử dụng để hiển thị trường trong khi 0 được sử dụng để ẩn các trường

cú pháp

Cú pháp cơ bản của phương thức find() với phép chiếu như sau -

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
7

Thí dụ

Hãy xem xét bộ sưu tập mycol có dữ liệu sau -

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
7

Ví dụ sau sẽ hiển thị tiêu đề của tài liệu trong khi truy vấn tài liệu

D:\set up\mongodb\bin>mongo.exe
MongoDB shell version: 2.4.6
connecting to: test
>db.test.save( { a: 1 } )
>db.test.find()
{ "_id" : ObjectId(5879b0f65a56a454), "a" : 1 }
>
9

Xin lưu ý trường _id luôn được hiển thị trong khi thực thi phương thức find(), nếu bạn không muốn trường này, thì bạn cần đặt nó thành 0

Trong chương này, chúng ta sẽ tìm hiểu cách giới hạn các bản ghi bằng MongoDB

Phương thức Giới hạn ()

Để giới hạn các bản ghi trong MongoDB, bạn cần sử dụng phương thức limit(). Phương thức chấp nhận một đối số kiểu số, là số lượng tài liệu mà bạn muốn hiển thị

cú pháp

Cú pháp cơ bản của phương thức limit() như sau -

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
D:\set up\mongodb\bin>mongo.exe
0

Thí dụ

Hãy xem xét bộ sưu tập myycol có dữ liệu sau

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
7

Ví dụ sau sẽ chỉ hiển thị hai tài liệu trong khi truy vấn tài liệu

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
D:\set up\mongodb\bin>mongo.exe
2

Nếu bạn không chỉ định đối số số trong phương thức limit() thì nó sẽ hiển thị tất cả các tài liệu từ bộ sưu tập

Phương thức bỏ qua MongoDB()

Ngoài phương thức limit(), còn có một phương thức khác là skip() cũng chấp nhận đối số kiểu số và được sử dụng để bỏ qua số lượng tài liệu

cú pháp

Cú pháp cơ bản của phương thức skip() như sau -

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
D:\set up\mongodb\bin>mongo.exe
3

Thí dụ

Ví dụ sau sẽ chỉ hiển thị tài liệu thứ hai

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
D:\set up\mongodb\bin>mongo.exe
4

Xin lưu ý, giá trị mặc định trong phương thức bỏ qua () là 0

Trong chương này, chúng ta sẽ tìm hiểu cách sắp xếp các bản ghi trong MongoDB

Phương thức sắp xếp()

Để sắp xếp tài liệu trong MongoDB, bạn cần sử dụng phương thức sort(). Phương thức chấp nhận một tài liệu chứa danh sách các trường cùng với thứ tự sắp xếp của chúng. Để chỉ định thứ tự sắp xếp 1 và -1 được sử dụng. 1 được sử dụng cho thứ tự tăng dần trong khi -1 được sử dụng cho thứ tự giảm dần

cú pháp

Cú pháp cơ bản của phương thức sort() như sau -

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
D:\set up\mongodb\bin>mongo.exe
5

Thí dụ

Hãy xem xét bộ sưu tập myycol có dữ liệu sau

C:\Users\XYZ>d:
D:\>cd "set up"
D:\set up>cd mongodb
D:\set up\mongodb>cd bin
D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
7

Ví dụ sau sẽ hiển thị các tài liệu được sắp xếp theo tiêu đề theo thứ tự giảm dần

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
D:\set up\mongodb\bin>mongo.exe
7

Xin lưu ý, nếu bạn không chỉ định tùy chọn sắp xếp, thì phương thức sort() sẽ hiển thị các tài liệu theo thứ tự tăng dần

Các chỉ mục hỗ trợ giải quyết hiệu quả các truy vấn. Không có chỉ mục, MongoDB phải quét mọi tài liệu của bộ sưu tập để chọn những tài liệu khớp với câu lệnh truy vấn. Quá trình quét này rất kém hiệu quả và yêu cầu MongoDB xử lý một khối lượng lớn dữ liệu

Chỉ mục là cấu trúc dữ liệu đặc biệt, lưu trữ một phần nhỏ của tập dữ liệu ở dạng dễ duyệt. Chỉ mục lưu trữ giá trị của một trường cụ thể hoặc tập hợp các trường, được sắp xếp theo giá trị của trường như được chỉ định trong chỉ mục

Phương thức createIndex()

Để tạo chỉ mục, bạn cần sử dụng phương thức createIndex() của MongoDB

cú pháp

Cú pháp cơ bản của phương thức createIndex() như sau()

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
D:\set up\mongodb\bin>mongo.exe
8

Ở đây khóa là tên của trường mà bạn muốn tạo chỉ mục và 1 là thứ tự tăng dần. Để tạo chỉ mục theo thứ tự giảm dần, bạn cần sử dụng -1

Thí dụ

D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" 
D:\set up\mongodb\bin>mongo.exe
9

Trong phương thức createIndex() bạn có thể truyền nhiều trường để tạo chỉ mục trên nhiều trường

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
0

Phương pháp này cũng chấp nhận danh sách các tùy chọn (không bắt buộc). Sau đây là danh sách -

Tham sốTypeDescriptionbackgroundBooleanXây dựng chỉ mục trong nền để việc xây dựng chỉ mục không chặn các hoạt động cơ sở dữ liệu khác. Chỉ định true để xây dựng trong nền. Giá trị mặc định là sai. uniqueBooleanTạo một chỉ mục duy nhất để bộ sưu tập không chấp nhận chèn tài liệu trong đó khóa chỉ mục hoặc các khóa khớp với giá trị hiện có trong chỉ mục. Chỉ định true để tạo một chỉ mục duy nhất. Giá trị mặc định là sai. namestringTên của chỉ mục. Nếu không được chỉ định, MongoDB tạo tên chỉ mục bằng cách nối tên của các trường được lập chỉ mục và thứ tự sắp xếp. thưaBooleanNếu đúng, chỉ mục chỉ tham chiếu các tài liệu có trường được chỉ định. Các chỉ mục này sử dụng ít không gian hơn nhưng hoạt động khác nhau trong một số trường hợp (đặc biệt là sắp xếp). Giá trị mặc định là sai. expireafterSecondsintegerChỉ định một giá trị, tính bằng giây, dưới dạng TTL để kiểm soát thời gian MongoDB lưu giữ các tài liệu trong bộ sưu tập này. weightsdocumentTrọng số là một số nằm trong khoảng từ 1 đến 99.999 và biểu thị tầm quan trọng của trường so với các trường được lập chỉ mục khác về mặt điểm số. default_languagestringĐối với chỉ mục văn bản, ngôn ngữ xác định danh sách các từ dừng và quy tắc cho trình tạo gốc và trình mã thông báo. Giá trị mặc định là tiếng Anh. language_overridestringĐối với chỉ mục văn bản, hãy chỉ định tên của trường trong tài liệu chứa ngôn ngữ để ghi đè ngôn ngữ mặc định. Giá trị mặc định là ngôn ngữ

Phương thức drop Index()

Bạn có thể xóa một chỉ mục cụ thể bằng phương thức dropIndex() của MongoDB

cú pháp

Cú pháp cơ bản của phương thức DropIndex() như sau()

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
1

Ở đây, "key" là tên của tệp mà bạn muốn xóa chỉ mục hiện có. Thay vì tài liệu đặc tả chỉ mục (cú pháp trên), bạn cũng có thể chỉ định trực tiếp tên của chỉ mục như

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
2

Thí dụ

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
3

Phương thức dropIndexes()

Phương pháp này xóa nhiều chỉ mục (được chỉ định) trên một bộ sưu tập

cú pháp

Cú pháp cơ bản của phương thức DropIndexes() như sau() -

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
4

Thí dụ

Giả sử chúng ta đã tạo 2 chỉ mục trong bộ sưu tập mycol được đặt tên như hình bên dưới -

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
5

Ví dụ sau loại bỏ các chỉ mục đã tạo ở trên của mycol −

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
6

Phương thức getIndexes()

Phương thức này trả về mô tả của tất cả các chỉ mục trong bộ sưu tập

cú pháp

Sau đây là cú pháp cơ bản của phương thức getIndexes() -

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
7

Thí dụ

Giả sử chúng ta đã tạo 2 chỉ mục trong bộ sưu tập mycol được đặt tên như hình bên dưới -

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
5

Ví dụ sau truy xuất tất cả các chỉ mục trong bộ sưu tập mycol −

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
9

Hoạt động tổng hợp xử lý bản ghi dữ liệu và trả về kết quả được tính toán. Hoạt động tổng hợp nhóm các giá trị từ nhiều tài liệu lại với nhau và có thể thực hiện nhiều thao tác khác nhau trên dữ liệu được nhóm để trả về một kết quả duy nhất. Trong SQL đếm (*) và với nhóm theo tương đương với tập hợp mongodb

Phương thức tổng hợp ()

Để tổng hợp trong MongoDB, bạn nên sử dụng phương thức tổng hợp ()

cú pháp

Cú pháp cơ bản của phương thức tổng hợp () như sau -

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' 
   | sudo tee /etc/apt/sources.list.d/mongodb.list
0

Thí dụ

Trong bộ sưu tập, bạn có dữ liệu sau -

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' 
   | sudo tee /etc/apt/sources.list.d/mongodb.list
1

Bây giờ từ bộ sưu tập trên, nếu bạn muốn hiển thị một danh sách cho biết có bao nhiêu hướng dẫn được viết bởi mỗi người dùng, thì bạn sẽ sử dụng phương thức tổng hợp () sau đây -

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' 
   | sudo tee /etc/apt/sources.list.d/mongodb.list
2

Truy vấn tương đương Sql cho trường hợp sử dụng trên sẽ được chọn by_user, đếm(*) từ nhóm mycol bởi by_user

Trong ví dụ trên, chúng tôi đã nhóm các tài liệu theo trường by_user và trên mỗi lần xuất hiện của by_user, giá trị tổng trước đó được tăng lên. Sau đây là danh sách các biểu thức tổng hợp có sẵn

ExpressionDescriptionExample$sumTổng hợp giá trị đã xác định từ tất cả các tài liệu trong bộ sưu tập. db. nấm mốc. tổng hợp([{$nhóm. {_Tôi. "$by_user", num_tutorial. {$sum. "$like"}}}])$avgTính giá trị trung bình của tất cả các giá trị đã cho từ tất cả các tài liệu trong bộ sưu tập. db. nấm mốc. tổng hợp([{$group. {_Tôi. "$by_user", num_tutorial. {$trung bình. "$like"}}}])$minNhận giá trị tối thiểu tương ứng từ tất cả các tài liệu trong bộ sưu tập. db. nấm mốc. tổng hợp([{$nhóm. {_Tôi. "$by_user", num_tutorial. {$ phút. "$like"}}}])$maxLấy giá trị tối đa tương ứng từ tất cả các tài liệu trong bộ sưu tập. db. nấm mốc. tổng hợp([{$group. {_Tôi. "$by_user", num_tutorial. {$tối đa. "$like"}}}])$pushChèn giá trị vào một mảng trong tài liệu kết quả. db. nấm mốc. tổng hợp([{$group. {_Tôi. "$by_user", url. {$push. "$url"}}}])$addToSet Chèn giá trị vào một mảng trong tài liệu kết quả nhưng không tạo ra các giá trị trùng lặp. db. nấm mốc. tổng hợp([{$nhóm. {_Tôi. "$by_user", url. {$addToSet. "$url"}}}])$firstLấy tài liệu đầu tiên từ tài liệu nguồn theo nhóm. Thông thường, điều này chỉ có ý nghĩa cùng với một số giai đoạn “$sort” được áp dụng trước đó. db. nấm mốc. tổng hợp([{$nhóm. {_Tôi. "$by_user", first_url. {$đầu tiên. "$url"}}}])$lastLấy tài liệu cuối cùng từ tài liệu nguồn theo nhóm. Thông thường, điều này chỉ có ý nghĩa cùng với một số giai đoạn “$sort” được áp dụng trước đó. db. nấm mốc. tổng hợp([{$group. {_Tôi. "$by_user", last_url. {$last. "$url"}}}])

Khái niệm đường ống

Trong lệnh UNIX, đường dẫn shell có nghĩa là khả năng thực hiện một thao tác trên một số đầu vào và sử dụng đầu ra làm đầu vào cho lệnh tiếp theo, v.v. MongoDB cũng hỗ trợ khái niệm tương tự trong khung tổng hợp. Có một tập hợp các giai đoạn có thể và mỗi giai đoạn đó được coi là một tập hợp tài liệu làm đầu vào và tạo ra một tập hợp tài liệu kết quả (hoặc tài liệu JSON kết quả cuối cùng ở cuối đường ống). Điều này sau đó có thể được sử dụng cho giai đoạn tiếp theo, v.v.

Sau đây là các giai đoạn có thể có trong khung tổng hợp -

  • $project - Được sử dụng để chọn một số trường cụ thể từ một bộ sưu tập

  • $match − Đây là thao tác lọc và do đó, điều này có thể làm giảm số lượng tài liệu được cung cấp làm đầu vào cho giai đoạn tiếp theo

  • $group - Điều này thực hiện tổng hợp thực tế như đã thảo luận ở trên

  • $sort - Sắp xếp tài liệu

  • $skip - Với điều này, có thể bỏ qua trong danh sách tài liệu cho một số lượng tài liệu nhất định

  • $limit - Điều này giới hạn số lượng tài liệu để xem, theo số đã cho bắt đầu từ các vị trí hiện tại

  • $unwind - Cái này được sử dụng để thư giãn tài liệu đang sử dụng mảng. Khi sử dụng một mảng, dữ liệu là loại được nối trước và thao tác này sẽ được hoàn tác với thao tác này để có lại các tài liệu riêng lẻ. Như vậy với giai đoạn này chúng ta sẽ tăng lượng tài liệu cho giai đoạn tiếp theo

Sao chép là quá trình đồng bộ hóa dữ liệu trên nhiều máy chủ. Bản sao cung cấp khả năng dự phòng và tăng tính khả dụng của dữ liệu với nhiều bản sao dữ liệu trên các máy chủ cơ sở dữ liệu khác nhau. Bản sao bảo vệ cơ sở dữ liệu khỏi sự mất mát của một máy chủ. Bản sao cũng cho phép bạn khôi phục sau lỗi phần cứng và gián đoạn dịch vụ. Với các bản sao bổ sung của dữ liệu, bạn có thể dành riêng một bản để khôi phục, báo cáo hoặc sao lưu sau thảm họa

Tại sao sao chép?

  • Để giữ an toàn cho dữ liệu của bạn
  • Dữ liệu sẵn có cao (24*7)
  • khắc phục thảm họa
  • Không có thời gian chết để bảo trì (như sao lưu, xây dựng lại chỉ mục, nén)
  • Tỷ lệ đọc (các bản sao bổ sung để đọc từ)
  • Bộ bản sao trong suốt đối với ứng dụng

Cách sao chép hoạt động trong MongoDB

MongoDB đạt được bản sao bằng cách sử dụng bộ bản sao. Bộ bản sao là một nhóm các phiên bản mongod lưu trữ cùng một bộ dữ liệu. Trong một bản sao, một nút là nút chính nhận tất cả các thao tác ghi. Tất cả các phiên bản khác, chẳng hạn như phiên bản thứ cấp, áp dụng các thao tác từ phiên bản chính để chúng có cùng một tập dữ liệu. Bộ bản sao chỉ có thể có một nút chính

  • Bộ bản sao là một nhóm gồm hai nút trở lên (thường yêu cầu tối thiểu 3 nút)

  • Trong một bộ bản sao, một nút là nút chính và các nút còn lại là nút phụ

  • Tất cả dữ liệu sao chép từ nút chính sang nút phụ

  • Tại thời điểm tự động chuyển đổi dự phòng hoặc bảo trì, cuộc bầu chọn được thiết lập cho nút chính và một nút chính mới được bầu chọn

  • Sau khi phục hồi nút bị lỗi, nó lại tham gia vào bộ bản sao và hoạt động như một nút phụ

Một sơ đồ điển hình về sao chép MongoDB được hiển thị trong đó ứng dụng khách luôn tương tác với nút chính và nút chính sau đó sao chép dữ liệu sang các nút phụ

Tài liệu mongodb được lưu trữ như thế nào?

Các tính năng của bộ bản sao

  • Một cụm gồm N nút
  • Bất kỳ một nút nào cũng có thể là nút chính
  • Tất cả các hoạt động ghi chuyển đến chính
  • chuyển đổi dự phòng tự động
  • Tự động phục hồi
  • Đồng thuận bầu cử sơ bộ

Thiết lập một bộ bản sao

Trong hướng dẫn này, chúng tôi sẽ chuyển đổi phiên bản MongoDB độc lập thành một bộ bản sao. Để chuyển đổi sang bộ bản sao, sau đây là các bước -

  • Tắt máy chủ MongoDB đang chạy

  • Khởi động máy chủ MongoDB bằng cách chỉ định -- tùy chọn replSet. Sau đây là cú pháp cơ bản của --replSet -

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' 
   | sudo tee /etc/apt/sources.list.d/mongodb.list
3

Thí dụ

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' 
   | sudo tee /etc/apt/sources.list.d/mongodb.list
4
  • Nó sẽ bắt đầu một phiên bản mongod với tên rs0, trên cổng 27017

  • Bây giờ bắt đầu dấu nhắc lệnh và kết nối với phiên bản mongod này

  • Trong ứng dụng khách Mongo, hãy ra lệnh rs. started() để bắt đầu một bộ bản sao mới

  • Để kiểm tra cấu hình bộ bản sao, hãy ra lệnh rs. conf(). Để kiểm tra trạng thái của bộ bản sao, hãy sử dụng lệnh rs. tình trạng()

Thêm thành viên vào bộ bản sao

Để thêm thành viên vào bộ bản sao, hãy bắt đầu phiên bản mongod trên nhiều máy. Bây giờ hãy bắt đầu một ứng dụng khách mongo và đưa ra lệnh rs. cộng()

cú pháp

Cú pháp cơ bản của rs. lệnh add() như sau -

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' 
   | sudo tee /etc/apt/sources.list.d/mongodb.list
5

Thí dụ

Giả sử tên ví dụ mongod của bạn là mongod1. net và nó đang chạy trên cổng 27017. Để thêm phiên bản này vào bộ bản sao, hãy ra lệnh rs. add() trong máy khách Mongo

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' 
   | sudo tee /etc/apt/sources.list.d/mongodb.list
6

Bạn chỉ có thể thêm phiên bản mongod vào bộ bản sao khi bạn được kết nối với nút chính. Để kiểm tra xem bạn có được kết nối với chính hay không, hãy ra lệnh db. isMaster() trong máy khách mongo

Sharding là quá trình lưu trữ các bản ghi dữ liệu trên nhiều máy và đó là cách tiếp cận của MongoDB để đáp ứng nhu cầu tăng trưởng dữ liệu. Khi kích thước của dữ liệu tăng lên, một máy đơn lẻ có thể không đủ để lưu trữ dữ liệu cũng như không cung cấp thông lượng đọc và ghi có thể chấp nhận được. Sharding giải quyết vấn đề với tỷ lệ ngang. Với sharding, bạn thêm nhiều máy hơn để hỗ trợ tăng trưởng dữ liệu và nhu cầu của hoạt động đọc và ghi

Tại sao Sharding?

  • Trong bản sao, tất cả ghi vào nút chính
  • Các truy vấn nhạy cảm về độ trễ vẫn chuyển sang chế độ chính
  • Bộ bản sao đơn có giới hạn 12 nút
  • Bộ nhớ không thể đủ lớn khi tập dữ liệu hoạt động lớn
  • Đĩa cục bộ không đủ lớn
  • Chia tỷ lệ dọc quá đắt

Phân mảnh trong MongoDB

Sơ đồ sau đây cho thấy sharding trong MongoDB sử dụng cụm sharding

Tài liệu mongodb được lưu trữ như thế nào?

Trong sơ đồ sau, có ba thành phần chính -

  • Phân đoạn - Phân đoạn được sử dụng để lưu trữ dữ liệu. Họ cung cấp tính sẵn sàng cao và tính nhất quán dữ liệu. Trong môi trường sản xuất, mỗi phân đoạn là một bộ bản sao riêng biệt

  • Máy chủ cấu hình - Máy chủ cấu hình lưu trữ siêu dữ liệu của cụm. Dữ liệu này chứa ánh xạ tập dữ liệu của cụm tới các phân đoạn. Bộ định tuyến truy vấn sử dụng siêu dữ liệu này để nhắm mục tiêu các hoạt động tới các phân đoạn cụ thể. Trong môi trường sản xuất, các cụm phân mảnh có chính xác 3 máy chủ cấu hình

  • Bộ định tuyến truy vấn - Bộ định tuyến truy vấn về cơ bản là các phiên bản mongo, giao diện với các ứng dụng khách và các hoạt động trực tiếp đến phân đoạn thích hợp. Bộ định tuyến truy vấn xử lý và nhắm mục tiêu các hoạt động tới các phân đoạn và sau đó trả về kết quả cho các máy khách. Một cụm sharded có thể chứa nhiều hơn một bộ định tuyến truy vấn để phân chia tải yêu cầu của máy khách. Một khách hàng gửi yêu cầu đến một bộ định tuyến truy vấn. Nói chung, một cụm sharded có nhiều bộ định tuyến truy vấn

Trong chương này, chúng ta sẽ xem cách tạo bản sao lưu trong MongoDB

Kết xuất dữ liệu MongoDB

Để tạo bản sao lưu cơ sở dữ liệu trong MongoDB, bạn nên sử dụng lệnh mongodump. Lệnh này sẽ kết xuất toàn bộ dữ liệu của máy chủ của bạn vào thư mục kết xuất. Có nhiều tùy chọn có sẵn để bạn có thể giới hạn lượng dữ liệu hoặc tạo bản sao lưu cho máy chủ từ xa của mình

cú pháp

Cú pháp cơ bản của lệnh mongodump như sau -

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' 
   | sudo tee /etc/apt/sources.list.d/mongodb.list
7

Thí dụ

Bắt đầu máy chủ mongod của bạn. Giả sử rằng máy chủ mongod của bạn đang chạy trên máy chủ cục bộ và cổng 27017, hãy mở dấu nhắc lệnh và chuyển đến thư mục bin của phiên bản mongodb của bạn và nhập lệnh mongodump

Hãy xem xét bộ sưu tập mycol có dữ liệu sau

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' 
   | sudo tee /etc/apt/sources.list.d/mongodb.list
7

Lệnh sẽ kết nối với máy chủ đang chạy ở 127. 0. 0. 1 và cổng 27017 và sao lưu tất cả dữ liệu của máy chủ vào thư mục /bin/dump/. Sau đây là đầu ra của lệnh -

Tài liệu mongodb được lưu trữ như thế nào?

Sau đây là danh sách các tùy chọn khả dụng có thể được sử dụng với lệnh mongodump

Cú phápMô tảExamplemongodump --host HOST_NAME --port PORT_NUMBER Lệnh này sẽ sao lưu tất cả cơ sở dữ liệu của phiên bản mongod đã chỉ định. mongodump --host hướng dẫn điểm. com --port 27017mongodump --dbpath DB_PATH --out BACKUP_DIRECTORY Lệnh này sẽ chỉ sao lưu cơ sở dữ liệu được chỉ định tại đường dẫn đã chỉ định. mongodump --dbpath /data/db/ --out /data/backup/mongodump --collection COLLECTION --db DB_NAME Lệnh này sẽ chỉ sao lưu bộ sưu tập được chỉ định của cơ sở dữ liệu đã chỉ định. mongodump --collection mycol --db test

Khôi phục dữ liệu

Để khôi phục dữ liệu sao lưu, lệnh mongorestore của MongoDB được sử dụng. Lệnh này khôi phục tất cả dữ liệu từ thư mục sao lưu

cú pháp

Cú pháp cơ bản của lệnh mongorestore là -

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' 
   | sudo tee /etc/apt/sources.list.d/mongodb.list
9

Sau đây là đầu ra của lệnh -

Tài liệu mongodb được lưu trữ như thế nào?

Khi bạn đang chuẩn bị triển khai MongoDB, bạn nên cố gắng hiểu ứng dụng của mình sẽ hoạt động như thế nào trong quá trình sản xuất. Bạn nên phát triển một cách tiếp cận nhất quán, có thể lặp lại để quản lý môi trường triển khai của mình để bạn có thể giảm thiểu bất kỳ sự bất ngờ nào khi bạn đang trong quá trình sản xuất

Cách tiếp cận tốt nhất là kết hợp tạo nguyên mẫu thiết lập của bạn, tiến hành kiểm tra tải, theo dõi các số liệu chính và sử dụng thông tin đó để mở rộng quy mô thiết lập của bạn. Phần quan trọng của phương pháp này là chủ động giám sát toàn bộ hệ thống của bạn - điều này sẽ giúp bạn hiểu hệ thống sản xuất của mình sẽ hoạt động như thế nào trước khi triển khai và xác định nơi bạn sẽ cần bổ sung công suất. Chẳng hạn, có cái nhìn sâu sắc về các đột biến tiềm năng trong việc sử dụng bộ nhớ của bạn, có thể giúp dập tắt một vụ cháy khóa ghi trước khi nó bắt đầu

Để theo dõi quá trình triển khai của bạn, MongoDB cung cấp một số lệnh sau –

mongostat

Lệnh này kiểm tra trạng thái của tất cả các phiên bản mongod đang chạy và trả về bộ đếm của các hoạt động cơ sở dữ liệu. Các bộ đếm này bao gồm chèn, truy vấn, cập nhật, xóa và con trỏ. Lệnh cũng hiển thị khi bạn gặp lỗi trang và hiển thị phần trăm khóa của bạn. Điều này có nghĩa là bạn sắp hết bộ nhớ, đạt đến khả năng ghi hoặc có một số vấn đề về hiệu suất

Để chạy lệnh, hãy bắt đầu phiên bản mongod của bạn. Trong một dấu nhắc lệnh khác, hãy chuyển đến thư mục bin của bản cài đặt mongodb của bạn và nhập mongostat

sudo apt-get update
0

Sau đây là đầu ra của lệnh -

Tài liệu mongodb được lưu trữ như thế nào?

cầy mangut

Lệnh này theo dõi và báo cáo hoạt động đọc và ghi của phiên bản MongoDB trên cơ sở bộ sưu tập. Theo mặc định, mongotop trả về thông tin theo từng giây, bạn có thể thay đổi thông tin này cho phù hợp. Bạn nên kiểm tra xem hoạt động đọc và ghi này có phù hợp với mục đích ứng dụng của bạn không và bạn không ghi quá nhiều lần ghi vào cơ sở dữ liệu cùng một lúc, đọc quá thường xuyên từ đĩa hoặc vượt quá kích thước cài đặt làm việc của bạn

Để chạy lệnh, hãy bắt đầu phiên bản mongod của bạn. Trong một dấu nhắc lệnh khác, hãy chuyển đến thư mục bin của bản cài đặt mongodb của bạn và nhập mongotop

sudo apt-get update
1

Sau đây là đầu ra của lệnh -

Tài liệu mongodb được lưu trữ như thế nào?

Để thay đổi lệnh mongotop để trả về thông tin ít thường xuyên hơn, hãy chỉ định một số cụ thể sau lệnh mongotop

sudo apt-get update
2

Ví dụ trên sẽ trả về giá trị cứ sau 30 giây

Ngoài các công cụ MongoDB, 10gen còn cung cấp dịch vụ giám sát được lưu trữ miễn phí, Dịch vụ quản lý MongoDB (MMS), cung cấp bảng điều khiển và cung cấp cho bạn chế độ xem các số liệu từ toàn bộ cụm của bạn

Trong chương này, chúng ta sẽ tìm hiểu cách thiết lập trình điều khiển MongoDB JDBC

Cài đặt

Trước khi bạn bắt đầu sử dụng MongoDB trong các chương trình Java của mình, bạn cần đảm bảo rằng bạn đã cài đặt trình điều khiển JDBC MongoDB và Java trên máy. Bạn có thể xem hướng dẫn Java để cài đặt Java trên máy của mình. Bây giờ, hãy để chúng tôi kiểm tra cách thiết lập trình điều khiển MongoDB JDBC

  • You need to download the jar from the path Download mongo. jar. Make sure to download the latest release of it

  • You need to include the mongo. jar into your classpath

Connect to Database

To connect database, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically

Following is the code snippet to connect to the database −

sudo apt-get update
3

Now, let's compile and run the above program to create our database myDb as shown below

sudo apt-get update
4

On executing, the above program gives you the following output

sudo apt-get update
5

Create a Collection

To create a collection, createCollection() method of com. mongodb. client. MongoDatabase class is used

Following is the code snippet to create a collection −

sudo apt-get update
6

On compiling, the above program gives you the following result −

sudo apt-get update
7

Getting/Selecting a Collection

To get/select a collection from the database, getCollection() method of com. mongodb. client. MongoDatabase class is used

Following is the program to get/select a collection −

sudo apt-get update
8

On compiling, the above program gives you the following result −

sudo apt-get update
9

Insert a Document

To insert a document into MongoDB, insert() method of com. mongodb. client. MongoCollection class is used

Following is the code snippet to insert a document −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
00

On compiling, the above program gives you the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
01

Retrieve All Documents

To select all documents from the collection, find() method of com. mongodb. client. MongoCollection class is used. This method returns a cursor, so you need to iterate this cursor

Following is the program to select all documents −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
02

On compiling, the above program gives you the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
03

Update Document

To update a document from the collection, updateOne() method of com. mongodb. client. MongoCollection class is used

Sau đây là chương trình để chọn tài liệu đầu tiên -

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
04

On compiling, the above program gives you the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
05

Delete a Document

To delete a document from the collection, you need to use the deleteOne() method of the com. mongodb. client. MongoCollection class

Following is the program to delete a document −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
06

On compiling, the above program gives you the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
07

Dropping a Collection

To drop a collection from a database, you need to use the drop() method of the com. mongodb. client. MongoCollection class

Following is the program to delete a collection −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
08

On compiling, the above program gives you the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
09

Listing All the Collections

To list all the collections in a database, you need to use the listCollectionNames() method of the com. mongodb. client. MongoDatabase class

Following is the program to list all the collections of a database −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
10

On compiling, the above program gives you the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
11

Remaining MongoDB methods save(), limit(), skip(), sort() etc. work same as explained in the subsequent tutorial

To use MongoDB with PHP, you need to use MongoDB PHP driver. Download the driver from the url Download PHP Driver. Make sure to download the latest release of it. Now unzip the archive and put php_mongo. dll in your PHP extension directory ("ext" by default) and add the following line to your php. ini file −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
12

Make a Connection and Select a Database

To make a connection, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically

Following is the code snippet to connect to the database −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
13

When the program is executed, it will produce the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
14

Create a Collection

Following is the code snippet to create a collection −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
15

When the program is executed, it will produce the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
16

Insert a Document

To insert a document into MongoDB, insert() method is used

Following is the code snippet to insert a document −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
17

When the program is executed, it will produce the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
18

Find All Documents

To select all documents from the collection, find() method is used

Following is the code snippet to select all documents −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
19

When the program is executed, it will produce the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
20

Update a Document

To update a document, you need to use the update() method

In the following example, we will update the title of inserted document to MongoDB Tutorial. Following is the code snippet to update a document −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
21

When the program is executed, it will produce the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
22

Delete a Document

To delete a document, you need to use remove() method

In the following example, we will remove the documents that has the title MongoDB Tutorial. Following is the code snippet to delete a document −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
23

When the program is executed, it will produce the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
24

In the above example, the second parameter is boolean type and used for justOne field of remove() method

Remaining MongoDB methods findOne(), save(), limit(), skip(), sort() etc. works same as explained above

Relationships in MongoDB represent how various documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1. 1, 1. N, N. 1 or N. N

Let us consider the case of storing addresses for users. So, one user can have multiple addresses making this a 1. N relationship

Following is the sample document structure of user document −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
25

Following is the sample document structure of address document −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
26

Modeling Embedded Relationships

In the embedded approach, we will embed the address document inside the user document

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
27

Cách tiếp cận này duy trì tất cả dữ liệu liên quan trong một tài liệu duy nhất, giúp dễ dàng truy xuất và bảo trì. Toàn bộ tài liệu có thể được truy xuất trong một truy vấn, chẳng hạn như -

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
28

Note that in the above query, db and users are the database and collection respectively

The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance

Mô hình hóa các mối quan hệ được tham chiếu

Đây là cách tiếp cận thiết kế mối quan hệ chuẩn hóa. Theo cách tiếp cận này, cả tài liệu người dùng và địa chỉ sẽ được duy trì riêng nhưng tài liệu người dùng sẽ chứa một trường sẽ tham chiếu trường id của tài liệu địa chỉ

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
29

Như đã trình bày ở trên, tài liệu người dùng chứa trường mảng address_ids chứa ObjectId của các địa chỉ tương ứng. Sử dụng các ObjectId này, chúng tôi có thể truy vấn các tài liệu địa chỉ và nhận thông tin chi tiết về địa chỉ từ đó. Với cách tiếp cận này, chúng ta sẽ cần hai truy vấn. đầu tiên để tìm nạp các trường address_ids từ tài liệu người dùng và thứ hai để tìm nạp các địa chỉ này từ bộ sưu tập địa chỉ

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
30

Như đã thấy trong chương trước về mối quan hệ MongoDB, để triển khai cấu trúc cơ sở dữ liệu được chuẩn hóa trong MongoDB, chúng tôi sử dụng khái niệm Mối quan hệ được tham chiếu còn được gọi là Tài liệu tham khảo thủ công trong đó chúng tôi lưu trữ id của tài liệu được tham chiếu theo cách thủ công bên trong tài liệu khác. Tuy nhiên, trong trường hợp tài liệu chứa các tham chiếu từ các bộ sưu tập khác nhau, chúng ta có thể sử dụng MongoDB DBRefs

DBRefs so với Tài liệu tham khảo thủ công

Như một tình huống ví dụ, nơi chúng tôi sẽ sử dụng DBRef thay vì tham chiếu thủ công, hãy xem xét cơ sở dữ liệu nơi chúng tôi đang lưu trữ các loại địa chỉ khác nhau (nhà riêng, văn phòng, gửi thư, v.v. ) trong các bộ sưu tập khác nhau (address_home, address_office, address_mailing, v.v.). Giờ đây, khi tài liệu của bộ sưu tập người dùng tham chiếu đến một địa chỉ, nó cũng cần chỉ định bộ sưu tập nào sẽ xem xét dựa trên loại địa chỉ. Trong các tình huống như vậy khi một tài liệu tham chiếu các tài liệu từ nhiều bộ sưu tập, chúng ta nên sử dụng DBRefs

Sử dụng DBRef

Có ba trường trong DBRefs -

  • $ref - Trường này chỉ định bộ sưu tập tài liệu được tham chiếu

  • $id − Trường này chỉ định trường _id của tài liệu được tham chiếu

  • $db − Đây là trường tùy chọn và chứa tên của cơ sở dữ liệu chứa tài liệu được tham chiếu

Hãy xem xét một tài liệu người dùng mẫu có địa chỉ trường DBRef như được hiển thị trong đoạn mã -

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
31

The address DBRef field here specifies that the referenced address document lies in address_home collection under tutorialspoint database and has an id of 534009e4d852427820000002

The following code dynamically looks in the collection specified by $ref parameter (address_home in our case) for a document with id as specified by $id parameter in DBRef

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
32

The above code returns the following address document present in address_home collection −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
33

In this chapter, we will learn about covered queries

What is a Covered Query?

As per the official MongoDB documentation, a covered query is a query in which −

  • All the fields in the query are part of an index
  • All the fields returned in the query are in the same index

Since all the fields present in the query are part of an index, MongoDB matches the query conditions and returns the result using the same index without actually looking inside the documents. Since indexes are present in RAM, fetching data from indexes is much faster as compared to fetching data by scanning documents

Using Covered Queries

To test covered queries, consider the following document in the users collection −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
34

We will first create a compound index for the users collection on the fields gender and user_name using the following query −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
35

Now, this index will cover the following query −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
36

That is to say that for the above query, MongoDB would not go looking into database documents. Instead it would fetch the required data from indexed data which is very fast

Since our index does not include _id field, we have explicitly excluded it from result set of our query, as MongoDB by default returns _id field in every query. So the following query would not have been covered inside the index created above −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
37

Lastly, remember that an index cannot cover a query if −

  • Any of the indexed fields is an array
  • Any of the indexed fields is a subdocument

Analyzing queries is a very important aspect of measuring how effective the database and indexing design is. We will learn about the frequently used $explain and $hint queries

Using $explain

The $explain operator provides information on the query, indexes used in a query and other statistics. It is very useful when analyzing how well your indexes are optimized

In the last chapter, we had already created an index for the users collection on fields gender and user_name using the following query −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
35

We will now use $explain on the following query −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
39

The above explain() query returns the following analyzed result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
40

We will now look at the fields in this result set −

  • The true value of indexOnly indicates that this query has used indexing

  • The cursor field specifies the type of cursor used. BTreeCursor type indicates that an index was used and also gives the name of the index used. BasicCursor indicates that a full scan was made without using any indexes

  • n indicates the number of documents matching returned

  • nscannedObjects indicates the total number of documents scanned

  • nscanned indicates the total number of documents or index entries scanned

Using $hint

The $hint operator forces the query optimizer to use the specified index to run a query. This is particularly useful when you want to test performance of a query with different indexes. For example, the following query specifies the index on fields gender and user_name to be used for this query −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
41

To analyze the above query using $explain −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
42

Model Data for Atomic Operations

The recommended approach to maintain atomicity would be to keep all the related information, which is frequently updated together in a single document using embedded documents. This would make sure that all the updates for a single document are atomic

Consider the following products document −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
43

In this document, we have embedded the information of the customer who buys the product in the product_bought_by field. Now, whenever a new customer buys the product, we will first check if the product is still available using product_available field. If available, we will reduce the value of product_available field as well as insert the new customer's embedded document in the product_bought_by field. We will use findAndModify command for this functionality because it searches and updates the document in the same go

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
44

Our approach of embedded document and using findAndModify query makes sure that the product purchase information is updated only if it the product is available. And the whole of this transaction being in the same query, is atomic

In contrast to this, consider the scenario where we may have kept the product availability and the information on who has bought the product, separately. In this case, we will first check if the product is available using the first query. Then in the second query we will update the purchase information. However, it is possible that between the executions of these two queries, some other user has purchased the product and it is no more available. Without knowing this, our second query will update the purchase information based on the result of our first query. This will make the database inconsistent because we have sold a product which is not available

Consider the following document of the users collection −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
45

The above document contains an address sub-document and a tags array

Indexing Array Fields

Suppose we want to search user documents based on the user’s tags. For this, we will create an index on tags array in the collection

Creating an index on array in turn creates separate index entries for each of its fields. So in our case when we create an index on tags array, separate indexes will be created for its values music, cricket and blogs

To create an index on tags array, use the following code −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
46

After creating the index, we can search on the tags field of the collection like this −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
47

To verify that proper indexing is used, use the following explain command −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
48

The above command resulted in "cursor" . "BtreeCursor tags_1" which confirms that proper indexing is used

Indexing Sub-Document Fields

Suppose that we want to search documents based on city, state and pincode fields. Since all these fields are part of address sub-document field, we will create an index on all the fields of the sub-document

For creating an index on all the three fields of the sub-document, use the following code −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
49

Once the index is created, we can search for any of the sub-document fields utilizing this index as follows −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
50

Remember that the query expression has to follow the order of the index specified. So the index created above would support the following queries −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
51

It will also support the following query −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
52

In this chapter, we will learn about Indexing Limitations and its other components

Extra Overhead

Every index occupies some space as well as causes an overhead on each insert, update and delete. So if you rarely use your collection for read operations, it makes sense not to use indexes

RAM Usage

Since indexes are stored in RAM, you should make sure that the total size of the index does not exceed the RAM limit. If the total size increases the RAM size, it will start deleting some indexes, causing performance loss

Query Limitations

Indexing can't be used in queries which use −

  • Regular expressions or negation operators like $nin, $not, etc
  • Arithmetic operators like $mod, etc
  • $where clause

Hence, it is always advisable to check the index usage for your queries

Index Key Limits

Starting from version 2. 6, MongoDB will not create an index if the value of existing index field exceeds the index key limit

Chèn tài liệu vượt quá giới hạn khóa chỉ mục

MongoDB sẽ không chèn bất kỳ tài liệu nào vào bộ sưu tập được lập chỉ mục nếu giá trị trường được lập chỉ mục của tài liệu này vượt quá giới hạn khóa chỉ mục. Tương tự với các tiện ích mongorestore và mongoimport

Phạm vi tối đa

  • Một bộ sưu tập không thể có nhiều hơn 64 chỉ mục
  • The length of the index name cannot be longer than 125 characters
  • A compound index can have maximum 31 fields indexed

We have been using MongoDB Object Id in all the previous chapters. In this chapter, we will understand the structure of ObjectId

An ObjectId is a 12-byte BSON type having the following structure −

  • The first 4 bytes representing the seconds since the unix epoch
  • The next 3 bytes are the machine identifier
  • The next 2 bytes consists of process id
  • The last 3 bytes are a random counter value

MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique

Creating New ObjectId

To generate a new ObjectId use the following code −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
53

The above statement returned the following uniquely generated id −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
54

Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
55

Creating Timestamp of a Document

Since the _id ObjectId by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document. You can fetch the creation time of a document using getTimestamp method −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
56

This will return the creation time of this document in ISO date format −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
57

Converting ObjectId to String

In some cases, you may need the value of ObjectId in a string format. To convert the ObjectId in string, use the following code −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
58

The above code will return the string format of the Guid −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
59

As per the MongoDB documentation, Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results. MongoDB uses mapReduce command for map-reduce operations. MapReduce is generally used for processing large data sets

MapReduce Command

Following is the syntax of the basic mapReduce command −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
60

The map-reduce function first queries the collection, then maps the result documents to emit key-value pairs, which is then reduced based on the keys that have multiple values

In the above syntax −

  • map is a javascript function that maps a value with a key and emits a key-value pair

  • giảm là một chức năng javascript làm giảm hoặc nhóm tất cả các tài liệu có cùng khóa

  • out specifies the location of the map-reduce query result

  • query specifies the optional selection criteria for selecting documents

  • sort specifies the optional sort criteria

  • limit specifies the optional maximum number of documents to be returned

Using MapReduce

Consider the following document structure storing user posts. The document stores user_name of the user and the status of post

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
61

Now, we will use a mapReduce function on our posts collection to select all the active posts, group them on the basis of user_name and then count the number of posts by each user using the following code −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
62

The above mapReduce query outputs the following result −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
63

The result shows that a total of 4 documents matched the query (status. "active"), the map function emitted 4 documents with key-value pairs and finally the reduce function grouped mapped documents having the same keys into 2

To see the result of this mapReduce query, use the find operator −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
64

The above query gives the following result which indicates that both users tom and mark have two posts in active states −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
65

In a similar manner, MapReduce queries can be used to construct large complex aggregation queries. The use of custom Javascript functions make use of MapReduce which is very flexible and powerful

Starting from version 2. 4, MongoDB started supporting text indexes to search inside string content. The Text Search uses stemming techniques to look for specified words in the string fields by dropping stemming stop words like a, an, the, etc. At present, MongoDB supports around 15 languages

Initially, Text Search was an experimental feature but starting from version 2. 6, the configuration is enabled by default. But if you are using the previous version of MongoDB, you have to enable text search with the following code −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
66

Creating Text Index

Consider the following document under posts collection containing the post text and its tags −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
67

We will create a text index on post_text field so that we can search inside our posts' text −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
68

Using Text Index

Now that we have created the text index on post_text field, we will search for all the posts having the word tutorialspoint in their text

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
69

The above command returned the following result documents having the word tutorialspoint in their post text −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
70

If you are using old versions of MongoDB, you have to use the following command −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
71

Using Text Search highly improves the search efficiency as compared to normal search

Deleting Text Index

To delete an existing text index, first find the name of index using the following query −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
72

After getting the name of your index from above query, run the following command. Here, post_text_text is the name of the index

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
73

Regular Expressions are frequently used in all languages to search for a pattern or word in any string. MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language

Unlike text search, we do not need to do any configuration or command to use regular expressions

Consider the following document structure under posts collection containing the post text and its tags −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
67

Using regex Expression

The following regex query searches for all the posts containing string tutorialspoint in it −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
75

The same query can also be written as −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
76

Using regex Expression with Case Insensitive

To make the search case insensitive, we use the $options parameter with value $i. The following command will look for strings having the word tutorialspoint, irrespective of smaller or capital case −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
77

One of the results returned from this query is the following document which contains the word tutorialspoint in different cases −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
78

Using regex for Array Elements

Chúng ta cũng có thể sử dụng khái niệm regex trên trường mảng. This is particularly very important when we implement the functionality of tags. Vì vậy, nếu bạn muốn tìm kiếm tất cả các bài đăng có thẻ bắt đầu từ từ hướng dẫn (hướng dẫn hoặc hướng dẫn hoặc điểm hướng dẫn hoặc hướng dẫn php), bạn có thể sử dụng đoạn mã sau -

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
79

Optimizing Regular Expression Queries

  • If the document fields are indexed, the query will use make use of indexed values to match the regular expression. This makes the search very fast as compared to the regular expression scanning the whole collection

  • If the regular expression is a prefix expression, all the matches are meant to start with a certain string characters. For e. g. , if the regex expression is ^tut, then the query has to search for only those strings that begin with tut

RockMongo is a MongoDB administration tool using which you can manage your server, databases, collections, documents, indexes, and a lot more. It provides a very user-friendly way for reading, writing, and creating documents. It is similar to PHPMyAdmin tool for PHP and MySQL

Downloading RockMongo

You can download the latest version of RockMongo from here. https. //github. com/iwind/rockmongo

Installing RockMongo

Once downloaded, you can unzip the package in your server root folder and rename the extracted folder to rockmongo. Open any web browser and access the index. php page from the folder rockmongo. Enter admin/admin as username/password respectively

Working with RockMongo

We will now be looking at some basic operations that you can perform with RockMongo

Creating New Database

To create a new database, click Databases tab. Click Create New Database. On the next screen, provide the name of the new database and click on Create. You will see a new database getting added in the left panel

Creating New Collection

To create a new collection inside a database, click on that database from the left panel. Click on the New Collection link on top. Provide the required name of the collection. Do not worry about the other fields of Is Capped, Size and Max. Click on Create. A new collection will be created and you will be able to see it in the left panel

Creating New Document

To create a new document, click on the collection under which you want to add documents. When you click on a collection, you will be able to see all the documents within that collection listed there. To create a new document, click on the Insert link at the top. You can enter the document's data either in JSON or array format and click on Save

Export/Import Data

To import/export data of any collection, click on that collection and then click on Export/Import link on the top panel. Follow the next instructions to export your data in a zip format and then import the same zip file to import back data

GridFS is the MongoDB specification for storing and retrieving large files such as images, audio files, video files, etc. It is kind of a file system to store files but its data is stored within MongoDB collections. GridFS has the capability to store files even greater than its document size limit of 16MB

GridFS divides a file into chunks and stores each chunk of data in a separate document, each of maximum size 255k

GridFS by default uses two collections fs. files and fs. chunks to store the file's metadata and the chunks. Each chunk is identified by its unique _id ObjectId field. The fs. files serves as a parent document. The files_id field in the fs. chunks document links the chunk to its parent

Following is a sample document of fs. files collection −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
80

The document specifies the file name, chunk size, uploaded date, and length

Following is a sample document of fs. chunks document −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
81

Adding Files to GridFS

Now, we will store an mp3 file using GridFS using the put command. For this, we will use the mongofiles. exe utility present in the bin folder of the MongoDB installation folder

Open your command prompt, navigate to the mongofiles. exe in the bin folder of MongoDB installation folder and type the following code −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
82

Here, gridfs is the name of the database in which the file will be stored. If the database is not present, MongoDB will automatically create a new document on the fly. Song. mp3 is the name of the file uploaded. To see the file's document in database, you can use find query −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
83

The above command returned the following document −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
84

We can also see all the chunks present in fs. chunks collection related to the stored file with the following code, using the document id returned in the previous query −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
85

In my case, the query returned 40 documents meaning that the whole mp3 document was divided in 40 chunks of data

Capped collections are fixed-size circular collections that follow the insertion order to support high performance for create, read, and delete operations. By circular, it means that when the fixed size allocated to the collection is exhausted, it will start deleting the oldest document in the collection without providing any explicit commands

Capped collections restrict updates to the documents if the update results in increased document size. Since capped collections store documents in the order of the disk storage, it ensures that the document size does not increase the size allocated on the disk. Capped collections are best for storing log information, cache data, or any other high volume data

Creating Capped Collection

To create a capped collection, we use the normal createCollection command but with capped option as true and specifying the maximum size of collection in bytes

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
86

In addition to collection size, we can also limit the number of documents in the collection using the max parameter −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
87

If you want to check whether a collection is capped or not, use the following isCapped command −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
88

If there is an existing collection which you are planning to convert to capped, you can do it with the following code −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
89

This code would convert our existing collection posts to a capped collection

Querying Capped Collection

By default, a find query on a capped collection will display results in insertion order. But if you want the documents to be retrieved in reverse order, use the sort command as shown in the following code −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
90

There are few other important points regarding capped collections worth knowing −

  • We cannot delete documents from a capped collection

  • There are no default indexes present in a capped collection, not even on _id field

  • While inserting a new document, MongoDB does not have to actually look for a place to accommodate new document on the disk. It can blindly insert the new document at the tail of the collection. Điều này làm cho thao tác chèn trong bộ sưu tập giới hạn rất nhanh

  • Similarly, while reading documents MongoDB returns the documents in the same order as present on disk. This makes the read operation very fast

MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents. However, there may be scenarios where we may want the _id field to have some auto-incremented value other than the ObjectId

Since this is not a default feature in MongoDB, we will programmatically achieve this functionality by using a counters collection as suggested by the MongoDB documentation

Using Counter Collection

Consider the following products document. We want the _id field to be an auto-incremented integer sequence starting from 1,2,3,4 upto n

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
91

For this, create a counters collection, which will keep track of the last sequence value for all the sequence fields

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
92

Now, we will insert the following document in the counters collection with productid as its key −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
93

The field sequence_value keeps track of the last value of the sequence

Use the following code to insert this sequence document in the counters collection −

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
94

Creating Javascript Function

Now, we will create a function getNextSequenceValue which will take the sequence name as its input, increment the sequence number by 1 and return the updated sequence number. In our case, the sequence name is productid

C:\>wmic os get osarchitecture
OSArchitecture
64-bit
C:\>
95

Using the Javascript Function

We will now use the function getNextSequenceValue while creating a new document and assigning the returned sequence value as document's _id field

Where are MongoDB documents stored?

By default Mongo stores its data in the directory /data/db . You can specify a different directory using the --dbpath option. If you're running Mongo on Windows then the directory will be C. \data\db , where C is the drive letter of the working directory in which Mongo was started.

How does MongoDB store data in database?

Để chèn dữ liệu vào bộ sưu tập MongoDB, bạn cần sử dụng phương thức insert() hoặc save() của MongoDB

Is MongoDB stored in memory?

MongoDB is not an in-memory database . Although it can be configured to run that way. But it makes liberal use of cache, meaning data records kept memory for fast retrieval, as opposed to on disk. There is much bad information on StackOverflow about what to do when your server runs out of memory.

How does MongoDB store and load data?

Summary .
Sign Up for a MongoDB Account
Create a Cluster
Add a Database User
Configure a Network Connection
Load Sample Data
Get Connection String