Làm cách nào để lấy dữ liệu từ MongoDB?
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
DatabaseDatabase is a physical container for collections. Each database gets its own set of files on the file system. A single MongoDB server typically has multiple databases CollectionCollection 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. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose DocumentA 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/sqlplusmongoSample DocumentFollowing 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
Tại sao nên sử dụng MongoDB?
Where to Use MongoDB?
Let us now see how to install MongoDB on Windows Install MongoDB On WindowsTo install MongoDB on Windows, first download the latest release of MongoDB from https. //www. mongodb. org/downloads. Make sure you get correct version of MongoDB depending upon your Windows version. To get your Windows version, open command prompt and execute the following command C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\> 32-bit versions of MongoDB only support databases smaller than 2GB and suitable only for testing and evaluation purposes Now extract your downloaded file to c. \ drive or any other location. Make sure the name of the extracted folder is mongodb-win32-i386-[version] or mongodb-win32-x86_64-[version]. Here [version] is the version of MongoDB download Next, open the command prompt and run the following command C:\>move mongodb-win64-* mongodb 1 dir(s) moved. C:\> In case you have extracted the MongoDB at different location, then go to that path by using command cd FOLDER/DIR and now run the above given process MongoDB requires a data folder to store its files. The default location for the MongoDB data directory is c. \data\db. So you need to create this folder using the Command Prompt. Execute the following command sequence C:\>md data C:\md data\db If you have to install the MongoDB at a different location, then you need to specify an alternate path for \data\db by setting the path dbpath in mongod. exe. Đối với cùng, đưa ra các lệnh sau In the command prompt, navigate to the bin directory present in the MongoDB installation folder. Suppose my installation folder is D. \set up\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" This will show waiting for connections message on the console output, which indicates that the mongod. exe process is running successfully Now to run the MongoDB, you need to open another command prompt and issue the following command 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 } > This will show that MongoDB is installed and run successfully. Next time when you run MongoDB, you need to issue only commands D:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe Install MongoDB on UbuntuRun the following command to import the MongoDB public GPG key − sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 Create a /etc/apt/sources. danh sách. d/mongodb. list file using the following command echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list Now issue the following command to update the repository − sudo apt-get update Next install the MongoDB by using the following command − C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>0 In the above installation, 2. 2. 3 is currently released MongoDB version. Make sure to install the latest version always. Now MongoDB is installed successfully Start MongoDBC:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>1 Stop MongoDBC:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>2 Restart MongoDBC:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>3 To use MongoDB run the following command C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>4 This will connect you to running MongoDB instance MongoDB HelpTo get a list of commands, type db. help() in MongoDB client. This will give you a list of commands as shown in the following screenshot MongoDB StatisticsTo get stats about MongoDB server, type the command db. stats() in MongoDB client. This will show the database name, number of collection and documents in the database. Output of the command is shown in the following screenshot Data in MongoDB has a flexible schema. documents in the same collection. They 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 Some considerations while designing Schema in MongoDB
ExampleSuppose a client needs a database design for his blog/website and see the differences between RDBMS and MongoDB schema design. Website has the following requirements
In RDBMS schema, design for above requirements will have minimum three tables While in MongoDB schema, design will have one collection post and the following structure − C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>5 So while showing the data, in RDBMS you need to join three tables and in MongoDB, data will be shown from one collection only Trong chương này, chúng ta sẽ xem cách tạo cơ sở dữ liệu trong MongoDB The use CommandMongoDB use DATABASE_NAME is used to create database. The command will create a new database if it doesn't exist, otherwise it will return the existing database SyntaxCú 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 ExampleIf you want to use a database with name , then use DATABASE statement would be as follows − C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>7 To check your currently selected database, use the command db C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>8 If you want to check your databases list, use the command show dbs C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>9 Your created database (mydb) is not present in list. Để 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ó SyntaxCú 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 ExampleĐầ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 SyntaxCú 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ụcTham 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ạnTrong 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 SyntaxCú pháp cơ bản của lệnh drop() như sau - C:\>md data C:\md data\db0 ExampleTrướ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\db1 Bây giờ thả bộ sưu tập với tên mycollection C:\>md data C:\md data\db2 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\db3 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à -
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 SyntaxCú pháp cơ bản của lệnh insert() như sau - C:\>md data C:\md data\db4 ExampleC:\>md data C:\md data\db5 Ở đâ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\db6 Để 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() ExampleC:\>md data C:\md data\db7 Để 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 SyntaxCú pháp cơ bản của phương thức find() như sau - C:\>md data C:\md data\db8 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() SyntaxC:\>md data C:\md data\db9 ExampleC:\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 != 50VÀ trong MongoDBSyntaxTrong 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 ExampleVí 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 MongoDBSyntaxĐể 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 ExampleVí 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 nhauExampleVí 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ó SyntaxCú 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 ExampleHã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 () MongoDBPhươ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() SyntaxCú 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 ExampleVí 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
SyntaxCú 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 ExampleHã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ộtNế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ệuNế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 SyntaxCú 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 ExampleHã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ị SyntaxCú 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.exe0 ExampleHã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.exe2 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 SyntaxCú 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.exe3 ExampleVí 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.exe4 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 SyntaxCú 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.exe5 ExampleHã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.exe7 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 SyntaxCú 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.exe8 Ở đâ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 ExampleD:\set up\mongodb\bin>mongod.exe --dbpath "d:\set up\mongodb\data" D:\set up\mongodb\bin>mongo.exe9 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 7F0CEB100 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 SyntaxCú 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 7F0CEB101 Ở đâ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 7F0CEB102 Examplesudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB103 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 SyntaxCú 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 7F0CEB104 ExampleGiả 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 7F0CEB105 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 7F0CEB106 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 SyntaxSau đâ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 7F0CEB107 ExampleGiả 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 7F0CEB105 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 7F0CEB109 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 () SyntaxCú 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.list0 ExampleTrong 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.list1 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.list2 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([{$group. {_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([{$group. {_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([{$group. {_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([{$group. {_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 ốngTrong 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 -
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?
How Replication Works in MongoDBMongoDB đạ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
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 Replica Set Features
Thiết lập một bộ bản saoTrong 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 -
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list3 Exampleecho 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list4
Add Members to Replica SetĐể 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() SyntaxCú 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.list5 ExampleGiả sử tên ví dụ mongod của bạn là mongod1. net và nó đang chạy trên cổng 27017. To add this instance to replica set, issue the command 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.list6 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() in mongo client 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?
Phân mảnh trong MongoDBThe following diagram shows the sharding in MongoDB using sharded cluster Trong sơ đồ sau, có ba thành phần chính -
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. This command will dump the entire data of your server into the dump directory. 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 SyntaxCú 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.list7 ExampleBắt đầu máy chủ mongod của bạn. Assuming that your mongod server is running on the localhost and port 27017, open a command prompt and go to the bin directory of your mongodb instance and type the command 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.list7 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/. Following is the output of the command − 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áp Mô 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_DIRECTORYThis command will backup only specified database at specified path. 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 testKhôi phục dữ liệuTo restore backup data MongoDB's mongorestore command is used. Lệnh này khôi phục tất cả dữ liệu từ thư mục sao lưu SyntaxCú 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.list9 Following is the output of the command − 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 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 chỉ số chính và sử dụng thông tin đó để mở rộng quy mô thiết lập của bạn. 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. 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 – mongostatLệ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ỏ. Command also shows when you’re hitting page faults, and showcase your lock percentage. Đ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. In another command prompt, go to bin directory of your mongodb installation and type mongostat sudo apt-get update0 Following is the output of the command − cầy mangutLệ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 update1 Following is the output of the command − To change mongotop command to return information less frequently, specify a specific number after the mongotop command sudo apt-get update2 The above example will return values every 30 seconds 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 InstallationBefore 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. 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
Connect to DatabaseĐể kết nối cơ sở dữ liệu, bạn cần chỉ định tên cơ sở dữ liệu, nếu cơ sở dữ liệu không tồn tại thì MongoDB sẽ tự động tạo nó Sau đây là đoạn mã để kết nối với cơ sở dữ liệu - sudo apt-get update3 Bây giờ, hãy biên dịch và chạy chương trình trên để tạo cơ sở dữ liệu myDb của chúng tôi như hình bên dưới sudo apt-get update4 Khi thực thi, chương trình trên cung cấp cho bạn đầu ra sau sudo apt-get update5 Create a CollectionTo create a collection, createCollection() method of com. mongodb. khách hàng. Lớp MongoDatabase được sử dụng Following is the code snippet to create a collection − sudo apt-get update6 On compiling, the above program gives you the following result − sudo apt-get update7 Lấy/Chọn một Bộ sưu tậpĐể lấy/chọn một bộ sưu tập từ cơ sở dữ liệu, phương thức getCollection() của com. mongodb. khách hàng. MongoDatabase class is used Sau đây là chương trình lấy/chọn một bộ sưu tập - sudo apt-get update8 On compiling, the above program gives you the following result − sudo apt-get update9 Chèn một tài liệuĐể chèn một tài liệu vào MongoDB, phương thức insert() của com. mongodb. khách hàng. lớp MongoCollection được sử dụng Sau đây là đoạn mã để chèn một tài liệu - 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 DocumentsTo select all documents from the collection, find() method of com. mongodb. khách hàng. lớp MongoCollection được sử dụng. Phương thức này trả về một con trỏ, vì vậy bạn cần lặp lại con trỏ này Sau đây là chương trình để chọn tất cả các tài liệu - 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 Cập nhật tài liệuĐể cập nhật tài liệu từ bộ sưu tập, phương thức updateOne() của com. mongodb. khách hàng. 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Để xóa một tài liệu khỏi bộ sưu tập, bạn cần sử dụng phương thức deleteOne() của com. mongodb. khách hàng. lớp MongoCollection Sau đây là chương trình xóa một tài liệu - 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 Thả một bộ sưu tậpĐể xóa một bộ sưu tập khỏi cơ sở dữ liệu, bạn cần sử dụng phương thức drop() của com. mongodb. client. lớp MongoCollection Sau đây là chương trình xóa một bộ sưu tập - 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ậpTo 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. làm việc tương tự như được giải thích trong hướng dẫn tiếp theo Để sử dụng MongoDB với PHP, bạn cần sử dụng trình điều khiển MongoDB PHP. 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. tập tin ini - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>12 Tạo kết nối và chọn cơ sở dữ liệuTo make a connection, you need to specify the database name, if the database doesn't exist then MongoDB creates it automatically Sau đây là đoạn mã để kết nối với cơ sở dữ liệu - 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 CollectionFollowing 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 Chèn một tài liệuTo insert a document into MongoDB, insert() method is used Sau đây là đoạn mã để chèn một tài liệu - 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 Tìm tất cả tài liệuĐể chọn tất cả các tài liệu từ bộ sưu tập, phương thức find() được sử dụng 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 Cập nhật tài liệuĐể cập nhật tài liệu, bạn cần sử dụng phương thức update() In the following example, we will update the title of inserted document to MongoDB Tutorial. Sau đây là đoạn mã để cập nhật tài liệu - 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 DocumentTo delete a document, you need to use remove() method Trong ví dụ sau, chúng tôi sẽ xóa các tài liệu có tiêu đề Hướng dẫn MongoDB. 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 Trong ví dụ trên, tham số thứ hai là kiểu boolean và được sử dụng cho trường justOne của phương thức remove() Remaining MongoDB methods findOne(), save(), limit(), skip(), sort() etc. hoạt động giống như giải thích ở trên Các mối quan hệ trong MongoDB thể hiện cách các tài liệu khác nhau có liên quan logic với nhau. Các mối quan hệ có thể được mô hình hóa thông qua các phương pháp được nhúng và tham chiếu. Những mối quan hệ như vậy có thể là 1. 1, 1. N, N. 1 or N. N Let us consider the case of storing addresses for users. Vì vậy, một người dùng có thể có nhiều địa chỉ làm cho địa chỉ này trở thành 1. N relationship Sau đây là cấu trúc tài liệu mẫu của tài liệu người dùng - 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 Mô hình hóa các mối quan hệ nhúngTrong cách tiếp cận nhúng, chúng tôi sẽ nhúng tài liệu địa chỉ bên trong tài liệu người dùng 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ì. 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 RelationshipsThis 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. 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ừ đó. 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. 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 vs Manual ReferencesAs 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 DBRefsCó ba trường trong DBRefs -
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 Đoạn mã sau tự động tìm trong bộ sưu tập được chỉ định bởi tham số $ref (address_home trong trường hợp của chúng tôi) để tìm tài liệu có id như được chỉ định bởi tham số $id trong 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 −
Vì tất cả các trường có trong truy vấn là một phần của chỉ mục, MongoDB khớp với các điều kiện truy vấn và trả về kết quả bằng cách sử dụng cùng một chỉ mục mà không thực sự nhìn vào bên trong tài liệu. Since indexes are present in RAM, fetching data from indexes is much faster as compared to fetching data by scanning documents Using Covered QueriesĐể kiểm tra các truy vấn được bảo hiểm, hãy xem xét tài liệu sau trong bộ sưu tập người dùng - 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 Bây giờ, chỉ mục này sẽ bao gồm truy vấn sau - 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. Vì vậy, truy vấn sau đây sẽ không được đề cập bên trong chỉ mục được tạo ở trên - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>37 Lastly, remember that an index cannot cover a query if −
Phân tích truy vấn là một khía cạnh rất quan trọng trong việc đo lường mức độ hiệu quả của cơ sở dữ liệu và thiết kế lập chỉ mục. Chúng ta sẽ tìm hiểu về các truy vấn $explain và $hint thường được sử dụng Using $explainThe $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 Bây giờ chúng ta sẽ xem xét các trường trong tập kết quả này -
Sử dụng gợi ý $The $hint operator forces the query optimizer to use the specified index to run a query. Điều này đặc biệt hữu ích khi bạn muốn kiểm tra hiệu suất của truy vấn với các chỉ mục khác nhau. 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 OperationsCách tiếp cận được đề xuất để duy trì tính nguyên tử là giữ tất cả thông tin liên quan, được cập nhật thường xuyên cùng nhau trong một tài liệu duy nhất bằng cách sử dụng tài liệu nhúng. This would make sure that all the updates for a single document are atomic Xem xét tài liệu sản phẩm sau đây - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>43 Trong tài liệu này, chúng tôi đã nhúng thông tin của khách hàng mua sản phẩm vào trường product_bought_by. 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. Và toàn bộ giao dịch này nằm trong cùng một truy vấn, là nguyên tử 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. Sau đó, trong truy vấn thứ hai, chúng tôi sẽ cập nhật thông tin mua hàng. 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 FieldsSuppose 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 FieldsSuppose 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. Vì vậy, chỉ mục được tạo ở trên sẽ hỗ trợ các truy vấn sau - 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 OverheadEvery 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 UsageSince 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 LimitationsIndexing can't be used in queries which use −
Hence, it is always advisable to check the index usage for your queries Index Key LimitsStarting 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 LimitMongoDB 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
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 −
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 ObjectIdTo 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 DocumentSince 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 StringIn 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 CommandFollowing 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 −
Using MapReduceConsider 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 Enabling Text SearchInitially, 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 IndexConsider 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 IndexNow 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 IndexTo 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 ExpressionThe 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 InsensitiveTo make the search case insensitive, we use the $options parameter with value $i. Lệnh sau sẽ tìm kiếm các chuỗi có từ tutorialspoint, bất kể chữ hoa hay chữ thường - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>77 Một trong những kết quả được trả về từ truy vấn này là tài liệu sau có chứa từ hướng dẫn trong các trường hợp khác nhau - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>78 Using regex for Array ElementsWe 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
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 RockMongoYou can download the latest version of RockMongo from here. https. //github. com/iwind/rockmongo Installing RockMongoOnce 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 RockMongoWe will now be looking at some basic operations that you can perform with RockMongo Creating New DatabaseTo 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 CollectionTo 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 DocumentTo 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 DataTo 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 GridFSBây giờ, chúng tôi sẽ lưu trữ một tệp mp3 bằng GridFS bằng lệnh put. For this, we will use the mongofiles. exe có trong thư mục bin của thư mục cài đặt MongoDB Mở dấu nhắc lệnh của bạn, điều hướng đến mongofiles. exe trong thư mục bin của thư mục cài đặt MongoDB và nhập mã sau - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>82 Ở đây, gridfs là tên của cơ sở dữ liệu mà tệp sẽ được lưu trữ. Nếu không có cơ sở dữ liệu, MongoDB sẽ tự động tạo một tài liệu mới một cách nhanh chóng. Bài hát. mp3 là tên của tệp được tải lên. Để xem tài liệu của tệp trong cơ sở dữ liệu, bạn có thể sử dụng truy vấn find - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>83 Lệnh trên trả về tài liệu sau - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>84 Chúng ta cũng có thể thấy tất cả các khối có trong fs. bộ sưu tập khối liên quan đến tệp được lưu trữ với mã sau, sử dụng id tài liệu được trả về trong truy vấn trước đó - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>85 Trong trường hợp của tôi, truy vấn trả về 40 tài liệu nghĩa là toàn bộ tài liệu mp3 được chia thành 40 khối dữ liệu Các bộ sưu tập được giới hạn là các bộ sưu tập hình tròn có kích thước cố định tuân theo thứ tự chèn để hỗ trợ hiệu suất cao cho các thao tác tạo, đọc và xóa. Theo thông tư, điều đó có nghĩa là khi hết kích thước cố định được phân bổ cho bộ sưu tập, nó sẽ bắt đầu xóa tài liệu cũ nhất trong bộ sưu tập mà không cung cấp bất kỳ lệnh rõ ràng nào Các bộ sưu tập được giới hạn hạn chế các bản cập nhật cho tài liệu nếu bản cập nhật dẫn đến kích thước tài liệu tăng lên. Vì các bộ sưu tập được giới hạn lưu trữ tài liệu theo thứ tự lưu trữ trên đĩa, nó đảm bảo rằng kích thước tài liệu không làm tăng kích thước được phân bổ trên đĩa. Các bộ sưu tập được giới hạn là tốt nhất để lưu trữ thông tin nhật ký, dữ liệu bộ đệm hoặc bất kỳ dữ liệu khối lượng lớn nào khác Tạo bộ sưu tập giới hạnĐể tạo một bộ sưu tập được giới hạn, chúng tôi sử dụng lệnh createCollection bình thường nhưng với tùy chọn capped là true và chỉ định kích thước tối đa của bộ sưu tập theo byte C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>86 Ngoài kích thước bộ sưu tập, chúng tôi cũng có thể giới hạn số lượng tài liệu trong bộ sưu tập bằng tham số max - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>87 Nếu bạn muốn kiểm tra xem một bộ sưu tập có bị giới hạn hay không, hãy sử dụng lệnh isCapped sau đây - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>88 Nếu có một bộ sưu tập hiện có mà bạn dự định chuyển đổi sang giới hạn, bạn có thể thực hiện điều đó bằng đoạn mã sau - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>89 Mã này sẽ chuyển đổi các bài đăng bộ sưu tập hiện tại của chúng tôi thành bộ sưu tập giới hạn Truy vấn bộ sưu tập giới hạnTheo mặc định, truy vấn tìm kiếm trên bộ sưu tập được giới hạn sẽ hiển thị kết quả theo thứ tự chèn. Nhưng nếu bạn muốn các tài liệu được truy xuất theo thứ tự ngược lại, hãy sử dụng lệnh sắp xếp như trong đoạn mã sau - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>90 Có một vài điểm quan trọng khác liên quan đến các bộ sưu tập giới hạn đáng để biết -
MongoDB không có chức năng tăng tự động vượt trội, như cơ sở dữ liệu SQL. Theo mặc định, nó sử dụng ObjectId 12 byte cho trường _id làm khóa chính để nhận dạng duy nhất các tài liệu. Tuy nhiên, có thể có các tình huống mà chúng ta có thể muốn trường _id có một số giá trị tăng tự động khác với ObjectId Vì đây không phải là một tính năng mặc định trong MongoDB, nên chúng tôi sẽ lập trình đạt được chức năng này bằng cách sử dụng bộ sưu tập bộ đếm theo đề xuất của tài liệu MongoDB Sử dụng bộ sưu tập truy cậpXem xét tài liệu sản phẩm sau. Chúng tôi muốn trường _id là một chuỗi số nguyên tăng dần tự động bắt đầu từ 1,2,3,4 cho đến n C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>91 Đối với điều này, hãy tạo một bộ sưu tập bộ đếm, bộ sưu tập này sẽ theo dõi giá trị chuỗi cuối cùng cho tất cả các trường chuỗi C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>92 Bây giờ, chúng ta sẽ chèn tài liệu sau vào bộ sưu tập counters với productid làm khóa của nó - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>93 Trường sequence_value theo dõi giá trị cuối cùng của chuỗi Sử dụng đoạn mã sau để chèn tài liệu trình tự này vào bộ sưu tập bộ đếm - C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>94 Tạo chức năng JavascriptBây giờ, chúng ta sẽ tạo một hàm getNextSequenceValue sẽ lấy tên dãy làm đầu vào, tăng số thứ tự lên 1 và trả về số thứ tự được cập nhật. Trong trường hợp của chúng tôi, tên trình tự là productid C:\>wmic os get osarchitecture OSArchitecture 64-bit C:\>95 Sử dụng chức năng JavascriptBây giờ chúng ta sẽ sử dụng hàm getNextSequenceValue trong khi tạo tài liệu mới và gán giá trị chuỗi được trả về làm trường _id của tài liệu Làm cách nào để tìm nạp dữ liệu từ MongoDB trong Java?Sử dụng chương trình Java . Tạo ứng dụng khách MongoDB bằng cách khởi tạo lớp MongoClient Kết nối với cơ sở dữ liệu bằng phương thức getDatabase() Lấy đối tượng của bộ sưu tập mà bạn muốn lấy tài liệu từ đó, sử dụng phương thức getCollection() Làm cách nào để lấy dữ liệu từ MongoDB sang HTML?Bạn phải làm theo các bước dưới đây để hiển thị dữ liệu MongoDB trên trang HTML. . Tạo ứng dụng Node Express js Cài đặt phụ thuộc cầy mangut flash ejs body-parser Kết nối ứng dụng với MongoDB Tạo mô hình Tạo tuyến đường Tạo bảng HTML và danh sách hiển thị Nhập mô-đun trong ứng dụng. js Khởi động máy chủ ứng dụng Làm cách nào để lấy dữ liệu từ MongoDB trong nút JS?Cách lấy dữ liệu từ mongodb trong Node js và hiển thị trong HTML (ejs) . Bước 1 – Tạo ứng dụng Node Express js Bước 2 – Cài đặt phụ thuộc cầy mangut flash ejs body-parser Bước 3 – Kết nối ứng dụng với MongoDB Bước 4 – Tạo mô hình Bước 5 – Tạo các tuyến đường Bước 6 – Tạo Bảng HTML và Danh sách Hiển thị Làm cách nào để lấy dữ liệu từ MongoDB bằng API?API dữ liệu Atlas MongoDB cho phép bạn đọc và ghi dữ liệu trong Atlas với các yêu cầu HTTPS tiêu chuẩn. Để sử dụng API dữ liệu, tất cả những gì bạn cần là ứng dụng khách HTTPS và khóa API hợp lệ. Máy khách gửi yêu cầu đến các điểm cuối cụ thể, mỗi điểm đại diện cho một hoạt động MongoDB. . Email/Mật khẩu Mã API JWT tùy chỉnh |