Bộ sưu tập trong mongodb là một nhóm?

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. Mỗi cơ sở dữ liệu có tập hợp tệp riêng trên hệ thống tệp. Một máy chủ MongoDB thường có nhiều cơ sở dữ liệu

Collection

Bộ sưu tập là một nhóm các tài liệu MongoDB. Nó tương đương với một bảng RDBMS. Một bộ sưu tập tồn tại trong một cơ sở dữ liệu duy nhất. Bộ sưu tập không thực thi lược đồ. Tài liệu trong một bộ sưu tập có thể có các trường khác nhau. Thông thường, tất cả các tài liệu trong một bộ sưu tập đều có mục đích tương tự hoặc liên quan

Tài liệu

Tài liệu là một tập hợp các cặp khóa-giá trị. Tài liệu có lược đồ động. Lược đồ động có nghĩa là các tài liệu trong cùng một bộ sưu tập 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 một bộ sưu tập có thể chứa các loại dữ liệu khác nhau

Bảng sau đây cho thấy mối quan hệ của thuật ngữ RDBMS với MongoDB

RDBMSMongoDBDatabaseDatabaseTableCollectionTuple/RowDocumentcolumnFieldTable JoinEmbedded DocumentsPrimary KeyPrimary Key (Khóa mặc định _id do chính mongodb cung cấp)Database Server and ClientMysqld/Oraclemongodmysql/sqlplusmongo

Tài liệu mẫu

Ví dụ sau hiển thị cấu trúc tài liệu của một trang blog, cấu trúc này chỉ đơn giản là một cặp giá trị khóa được phân tách bằng dấu phẩy

{
   _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 là một số thập lục phân 12 byte đảm bảo tính duy nhất của mọi tài liệu. Bạn có thể cung cấp _id trong khi chèn tài liệu. Nếu bạn không cung cấp thì MongoDB cung cấp một id duy nhất cho mọi tài liệu. 12 byte này, 4 byte đầu tiên cho dấu thời gian hiện tại, 3 byte tiếp theo cho id máy, 2 byte tiếp theo cho id tiến trình của máy chủ MongoDB và 3 byte còn lại là GIÁ TRỊ gia tăng đơn giản

Bất kỳ cơ sở dữ liệu quan hệ nào cũng có thiết kế lược đồ điển hình hiển thị số lượng bảng và mối quan hệ giữa các bảng này. Trong khi ở MongoDB, không có khái niệm về mối quan hệ

Ưu điểm của MongoDB so với RDBMS

  • Schema less − MongoDB là một cơ sở dữ liệu tài liệu trong đó một bộ sưu tập chứa các tài liệu khác nhau. Số lượng trường, nội dung và kích thước của tài liệu có thể khác nhau từ tài liệu này sang tài liệu khác

  • Cấu trúc của một đối tượng rõ ràng

  • Không có kết nối phức tạp

  • Khả năng truy vấn sâu. MongoDB hỗ trợ các truy vấn động trên tài liệu bằng ngôn ngữ truy vấn dựa trên tài liệu mạnh gần bằng SQL

  • điều chỉnh

  • Dễ dàng mở rộng quy mô − MongoDB dễ dàng mở rộng quy mô

  • Không cần chuyển đổi/ánh xạ các đối tượng ứng dụng sang các đối tượng cơ sở dữ liệu

  • Sử dụng bộ nhớ trong để lưu trữ bộ làm việc (có cửa sổ), cho phép truy cập dữ liệu nhanh hơn

Tại sao nên sử dụng 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

  • Auto-sharding

  • Rich queries

  • Fast in-place updates

  • Professional support by MongoDB

Where to Use MongoDB?

  • Dữ liệu lớn
  • Content Management and Delivery
  • Mobile and Social Infrastructure
  • 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

Install MongoDB On 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. Đảm bảo tên của thư mục được giải nén là mongodb-win32-i386-[version] hoặc 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 ở vị trí khác, 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

Bộ sưu tập trong mongodb là một nhóm?

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

Bộ sưu tập trong mongodb là một nhóm?

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. Trang web 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ẻ
  • Mỗi bài đăng có tên của nhà xuất bản và tổng số lượt thích
  • 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

Bộ sưu tập trong mongodb là một nhóm?

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() lệnh được sử dụng để xóa cơ sở dữ liệu hiện có

cú pháp

Basic syntax of dropDatabase() command is as follows −

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

  • Integer − This type is used to store a numerical value. 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 phẩy độ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

By default, MongoDB will update only a single document. Để 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()

To sort documents in MongoDB, you need to use sort() method. 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([{$nhóm. {_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. {_nhận dạng. "$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([{$nhóm. {_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. {_nhận dạng. "$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. {_nhận dạng. "$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([{$nhóm. {_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 − With this, it is possible to skip forward in the list of documents for a given amount of documents

  • $limit − This limits the amount of documents to look at, by the given number starting from the current positions

  • $unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage

Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers. Replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup

Why Replication?

  • To keep your data safe
  • High (24*7) availability of data
  • Disaster recovery
  • No downtime for maintenance (like backups, index rebuilds, compaction)
  • Read scaling (extra copies to read from)
  • Replica set is transparent to the application

How Replication Works in MongoDB

MongoDB achieves replication by the use of replica set. A replica set is a group of mongod instances that host the same data set. In a replica, one node is primary node that receives all write operations. All other instances, such as secondaries, apply operations from the primary so that they have the same data set. Replica set can have only one primary node

  • Replica set is a group of two or more nodes (generally minimum 3 nodes are required)

  • In a replica set, one node is primary node and remaining nodes are secondary

  • All data replicates from primary to secondary node

  • At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected

  • After the recovery of failed node, it again join the replica set and works as a secondary node

A typical diagram of MongoDB replication is shown in which client application always interact with the primary node and the primary node then replicates the data to the secondary nodes

Bộ sưu tập trong mongodb là một nhóm?

Replica Set Features

  • A cluster of N nodes
  • Any one node can be primary
  • All write operations go to primary
  • Automatic failover
  • Automatic recovery
  • Consensus election of primary

Set Up a Replica Set

In this tutorial, we will convert standalone MongoDB instance to a replica set. To convert to replica set, following are the steps −

  • Shutdown already running MongoDB server

  • Start the MongoDB server by specifying -- replSet option. Following is the basic syntax of --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
  • It will start a mongod instance with the name rs0, on port 27017

  • Now start the command prompt and connect to this mongod instance

  • In Mongo client, issue the command rs. initiate() to initiate a new replica set

  • To check the replica set configuration, issue the command rs. conf(). To check the status of replica set issue the command rs. status()

Add Members to Replica Set

To add members to replica set, start mongod instances on multiple machines. Now start a mongo client and issue a command rs. add()

cú pháp

The basic syntax of rs. add() command is as follows −

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

Thí dụ

Suppose your mongod instance name is mongod1. net and it is running on port 27017. To add this instance to replica set, issue the command rs. add() in Mongo client

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

You can add mongod instance to replica set only when you are connected to primary node. To check whether you are connected to primary or not, issue the command db. isMaster() in mongo client

Sharding is the process of storing data records across multiple machines and it is MongoDB's approach to meeting the demands of data growth. As the size of the data increases, a single machine may not be sufficient to store the data nor provide an acceptable read and write throughput. Sharding solves the problem with horizontal scaling. With sharding, you add more machines to support data growth and the demands of read and write operations

Why Sharding?

  • In replication, all writes go to master node
  • Latency sensitive queries still go to master
  • Single replica set has limitation of 12 nodes
  • Memory can't be large enough when active dataset is big
  • Local disk is not big enough
  • Vertical scaling is too expensive

Sharding in MongoDB

The following diagram shows the sharding in MongoDB using sharded cluster

Bộ sưu tập trong mongodb là một nhóm?

In the following diagram, there are three main components −

  • Shards − Shards are used to store data. They provide high availability and data consistency. In production environment, each shard is a separate replica set

  • Config Servers − Config servers store the cluster's metadata. This data contains a mapping of the cluster's data set to the shards. The query router uses this metadata to target operations to specific shards. In production environment, sharded clusters have exactly 3 config servers

  • Query Routers − Query routers are basically mongo instances, interface with client applications and direct operations to the appropriate shard. The query router processes and targets the operations to shards and then returns results to the clients. A sharded cluster can contain more than one query router to divide the client request load. A client sends requests to one query router. Generally, a sharded cluster have many query routers

In this chapter, we will see how to create a backup in MongoDB

Dump MongoDB Data

To create backup of database in MongoDB, you should use mongodump command. This command will dump the entire data of your server into the dump directory. There are many options available by which you can limit the amount of data or create backup of your remote server

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 -

Bộ sưu tập trong mongodb là một nhóm?

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 tutorialspoint. 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

The basic syntax of mongorestore command is −

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

Following is the output of the command −

Bộ sưu tập trong mongodb là một nhóm?

When you are preparing a MongoDB deployment, you should try to understand how your application is going to hold up in production. It’s a good idea to develop a consistent, repeatable approach to managing your deployment environment so that you can minimize any surprises once you’re in production

The best approach incorporates prototyping your set up, conducting load testing, monitoring key metrics, and using that information to scale your set up. The key part of the approach is to proactively monitor your entire system - this will help you understand how your production system will hold up before deploying, and determine where you will need to add capacity. Having insight into potential spikes in your memory usage, for example, could help put out a write-lock fire before it starts

To monitor your deployment, MongoDB provides some of the following commands −

mongostat

This command checks the status of all running mongod instances and return counters of database operations. These counters include inserts, queries, updates, deletes, and cursors. Command also shows when you’re hitting page faults, and showcase your lock percentage. This means that you're running low on memory, hitting write capacity or have some performance issue

To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongostat

sudo apt-get update
0

Following is the output of the command −

Bộ sưu tập trong mongodb là một nhóm?

mongotop

This command tracks and reports the read and write activity of MongoDB instance on a collection basis. By default, mongotop returns information in each second, which you can change it accordingly. You should check that this read and write activity matches your application intention, and you’re not firing too many writes to the database at a time, reading too frequently from a disk, or are exceeding your working set size

To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongotop

sudo apt-get update
1

Following is the output of the command −

Bộ sưu tập trong mongodb là một nhóm?

To change mongotop command to return information less frequently, specify a specific number after the mongotop command

sudo apt-get update
2

The above example will return values every 30 seconds

Apart from the MongoDB tools, 10gen provides a free, hosted monitoring service, MongoDB Management Service (MMS), that provides a dashboard and gives you a view of the metrics from your entire cluster

In this chapter, we will learn how to set up MongoDB JDBC driver

Installation

Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB JDBC driver and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB JDBC driver

  • 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

Following is the program to select the first document −

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

Liệt kê tất cả các bộ sưu tập

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

Các phương thức MongoDB còn lại save(), limit(), skip(), sort(), v.v. work same as explained in the subsequent tutorial

Để sử dụng MongoDB với PHP, bạn cần sử dụng trình điều khiển MongoDB PHP. Tải xuống trình điều khiển từ url Tải xuống trình điều khiển PHP. 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

This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. The whole document can be retrieved in a single query such as −

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

Modeling Referenced Relationships

This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document's id field

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

As shown above, the user document contains the array field address_ids which contains ObjectIds of corresponding addresses. Using these ObjectIds, we can query the address documents and get address details from there. With this approach, we will need two queries. first to fetch the address_ids fields from user document and second to fetch these addresses from address collection

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

As seen in the last chapter of MongoDB relationships, to implement a normalized database structure in MongoDB, we use the concept of Referenced Relationships also referred to as Manual References in which we manually store the referenced document's id inside other document. However, in cases where a document contains references from different collections, we can use MongoDB DBRefs

DBRefs vs Manual References

As an example scenario, where we would use DBRefs instead of manual references, consider a database where we are storing different types of addresses (home, office, mailing, etc. ) in different collections (address_home, address_office, address_mailing, etc). Now, when a user collection's document references an address, it also needs to specify which collection to look into based on the address type. In such scenarios where a document references documents from many collections, we should use DBRefs

Using DBRefs

Có ba trường trong DBRefs -

  • $ref − This field specifies the collection of the referenced document

  • $id − This field specifies the _id field of the referenced document

  • $db − This is an optional field and contains the name of the database in which the referenced document lies

Consider a sample user document having DBRef field address as shown in the code snippet −

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

Cuối cùng, hãy nhớ rằng một chỉ mục không thể bao gồm một truy vấn nếu -

  • 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. Chúng ta sẽ tìm hiểu về các truy vấn $explain và $hint thường được sử dụng

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

Truy vấn giải thích () ở trên trả về kết quả được phân tích sau -

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. Vì vậy, nếu bạn hiếm khi sử dụng bộ sưu tập của mình cho các thao tác đọc, bạn không nên sử dụng các chỉ mục

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

Inserting Documents Exceeding Index Key Limit

MongoDB will not insert any document into an indexed collection if the indexed field value of this document exceeds the index key limit. Same is the case with mongorestore and mongoimport utilities

Maximum Ranges

  • A collection cannot have more than 64 indexes
  • 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

We can also use the concept of regex on array field. This is particularly very important when we implement the functionality of tags. So, if you want to search for all the posts having tags beginning from the word tutorial (either tutorial or tutorials or tutorialpoint or tutorialphp), you can use the following code −

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. Đừng lo lắng về các trường khác của Is Capped, Size và Max. Nhấp vào Tạo. Một bộ sưu tập mới sẽ được tạo và bạn có thể nhìn thấy nó trong bảng điều khiển bên trái

Tạo tài liệu mới

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. This makes insert operations in capped collections very fast

  • 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

Is collection a group of MongoDB documents?

Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table . A collection exists within a single database. Collections do not enforce a schema.

What is a collection in a MongoDB?

A collection is a grouping of MongoDB documents . Documents within a collection can have different fields. A collection is the equivalent of a table in a relational database system.

What is a group of documents called in MongoDB?

MongoDB stores documents in collections. Collections are analogous to tables in relational databases

WHAT IS group in MongoDB?

$group. Giai đoạn $group phân tách tài liệu thành các nhóm theo "khóa nhóm" . Đầu ra là một tài liệu cho mỗi khóa nhóm duy nhất. Khóa nhóm thường là một trường hoặc nhóm trường. The group key can also be the result of an expression.