# Lập chỉ mục các trường mảng trong MongoDB

Giả sử rằng chúng ta muốn tìm kiếm trong user document dựa vào các tags. Để thực hiện điều này, chúng ta sẽ tạo một chỉ mục trên mảng tags trong Collection đó.

Tạo một chỉ mục trên mảng tức là tạo các chỉ mục riêng rẽ cho mỗi trường của nó. Vì thế trong tình huống này, khi chúng ta tạo chỉ mục trên mảng tags, các chỉ mục riêng rẽ sẽ được tạo cho các giá trị của nó là music, cricket và blogs.

Để tạo một chỉ mục trên mảng tags, bạn sử dụng:

```
>db.users.ensureIndex\({"tags":1}\)
```

Sau khi tạo chỉ mục, chúng ta có thể thực hiện tìm kiếm trên trường tags của Collection đó giống như sau:

```
>db.users.find\({tags:"cricket"}\)
```

Để kiểm tra xem chỉ mục hợp lý đã được sử dụng, bạn sử dụng lệnh **explain**.

```
>db.users.find\({tags:"cricket"}\).explain\(\)
```

Lệnh explain trên trả về kết quả trong "cursor" : "BtreeCursor tags\_1" mà xác nhận rằng chỉ mục hợp lý được sử dụng.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://janeto.gitbook.io/mongodb-toan-tap/hoat-dong-chi-muc-nang-cao-trong-mongodb/lap-chi-muc-cac-truong-mang-trong-mongodb.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
