Cách tạo cơ sở dữ liệu và bộ sưu tập trong MongoDB

⚡ Tóm tắt thông minh

How to Create Database and Collection in MongoDB is the first basic step for storing data. This resource explains creating a database with the use command, creating a collection with insert(), adding documents, and extends into reading documents with find() and dropping collections and databases.

  • 🗄️ Tạo nên cơ sở dữ liệu: The use command creates and switches to a database.
  • 📁 Create Collection: Inserting a first record creates the collection automatically.
  • Insert Documents: The insert() command adds documents with field names and values.
  • 🔍 Read Documents: The find() method queries and returns stored documents.
  • 🗑️ Rơi vãi: drop() removes a collection and dropDatabase() removes a database.

Tạo cơ sở dữ liệu và bộ sưu tập trong MongoDB

In MongoDB, the first basic step is to have a database and collection in place. The database is used to store all of the collections, and the collection in turn is used to store all of the documents. The documents in turn will contain the relevant field name and field values.

The snapshot above shows a basic example of how a document would look. The field names of the document are “Employeeid” and “EmployeeName”, and the field values are “1” and “Smith” respectively. A bunch of documents would then make up a collection in MongoDB.

Tạo cơ sở dữ liệu bằng lệnh “use”

Tạo cơ sở dữ liệu trong MongoDB đơn giản như việc ban hành “sử dụng”. Ví dụ sau đây cho thấy cách thực hiện điều này.

Creating a Database using use Command

Code Giải thích:

  • "sử dụng" lệnh được sử dụng để tạo cơ sở dữ liệu trong MongoDB. If the database does not exist, a new one will be created.

If the command is executed successfully, the following output will be shown:

Đầu ra:

Creating a Database using use Command

MongoDB sẽ tự động chuyển sang cơ sở dữ liệu sau khi được tạo.

Tạo Bộ sưu tập/Bảng bằng cách sử dụng Insert()

The easiest way to create a collection is to insert a record (which is nothing but a document consisting of field names and values) into a collection. If the collection does not exist, a new one will be created. The following example shows how this can be done.

db.Employee.insert
(
	{
		"Employeeid" : 1,
		"EmployeeName" : "Martin"
	}
)

Code Giải thích:

  • Như đã thấy ở trên, bằng cách sử dụng "chèn" lệnh bộ sưu tập sẽ được tạo.

Thêm tài liệu bằng lệnh Insert()

MongoDB cung cấp insert() command để chèn tài liệu vào bộ sưu tập. Ví dụ sau đây cho thấy cách thực hiện điều này.

Bước 1) Write the “insert” command.

Bước 2) Within the “insert” command, add the required field name and field value for the document which needs to be created.

Thêm tài liệu bằng lệnh Insert()

Code Giải thích:

  1. Phần đầu tiên của lệnh là “insert statement“, which is the statement used to insert a document into the collection.
  2. The second part of the statement is to add the field name and the field value, in other words, what the document in the collection is going to contain.

If the command is executed successfully, the following output will be shown:

Đầu ra:

Thêm tài liệu bằng lệnh Insert()

Kết quả đầu ra cho thấy thao tác được thực hiện là thao tác chèn và một bản ghi đã được chèn vào bộ sưu tập.

How to Query Documents in MongoDB using find()

After inserting documents, the next step is to read them back. MongoDB provides the find() method to query documents in a collection. This is the “read” operation in CRUD (Create, Read, Update, Delete).

To display all documents in the Employee collection, run the command below:

db.Employee.find()

The output of find() can be difficult to read on a single line. To display the documents in a formatted, easy-to-read structure, append the pretty() method:

db.Employee.find().pretty()

You can also filter the results by passing a query condition. For example, to find only the employee whose Employeeid is 1, pass a field-value pair to find():

db.Employee.find({ "Employeeid" : 1 })

Code Giải thích:

  • find() with no argument returns every document in the collection as a cursor.
  • Passing a field-value pair, such as {“Employeeid”: 1}, returns only the documents that match that condition.
  • The findOne() method works the same way but returns just the first matching document instead of a cursor.

This read operation is the most common way to retrieve stored data from a MongoDB bộ sưu tập.

How to Drop a Collection and Database in MongoDB

When a collection or database is no longer needed, MongoDB lets you remove it. To drop a single collection, switch to its database and run the drop() method:

db.Employee.drop()

This deletes the Employee collection along with all of its documents. The command returns đúng when the collection is dropped successfully.

To drop the entire current database, run the dropDatabase() command:

db.dropDatabase()

This removes the database you are currently using, along with all of its collections. Keep the following cautions in mind before dropping:

  • Rơiping is permanent and cannot be undone, so back up important data first.
  • Make sure you are connected to the correct database before running dropDatabase().
  • Use these commands carefully, especially in production environments.

Câu Hỏi Thường Gặp

Yes. AI assistants can turn a plain-English request into MongoDB shell commands such as insert(), find(), and update(). You should review the generated query and test it before running it on real data.

Yes. AI tools can translate SQL statements into equivalent MongoDB find, insert, and aggregate commands. This helps developers moving from relational databases, though complex joins may need manual restructuring into embedded documents.

insert() can add one or many documents and is now legacy. insertOne() adds a single document and insertMany() adds several. The newer methods return clearer acknowledgements and are recommended today.

Use updateOne() or updateMany() with a filter and a $set operator. For example, db.Employee.updateOne({Employeeid:1}, {$set:{EmployeeName:”John”}}) changes the name of the matching document.

Tóm tắt bài viết này với: