> For the complete documentation index, see [llms.txt](https://janeto.gitbook.io/mongodb-toan-tap/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://janeto.gitbook.io/mongodb-toan-tap/auto-increment-sequence-trong-mongodb/su-dung-ham-javascript.md).

# Sử dụng hàm JavaScript

Giờ chúng ta sử dụng hàm getNextSequenceValue trong khi tạo một Document mới và gán giá trị dãy đã trả về như là trường \_id của Document đó.

Chèn hai Document mẫu bởi sử dụng code sau:

```
>db.products.insert({

"_id":getNextSequenceValue("productid"),

"product_name":"Apple iPhone",

"category":"mobiles"})

>db.products.insert({

"_id":getNextSequenceValue("productid"),

"product_name":"Samsung S3",

"category":"mobiles"})
```

Như bạn thấy, chúng ta đã sử dụng hàm getNextSequenceValue để thiết lập giá trị cho trường \_id.

Để kiểm tra tính năng này, chúng ta lấy các Document bởi sử dụng lệnh find:

```
>db.prodcuts.find()

Truy vấn trên trả về các Document có trường _id là tự động tăng.

{ "_id" : 1, "product_name" : "Apple iPhone", "category" : "mobiles"}

{ "_id" : 2, "product_name" : "Samsung S3", "category" : "mobiles" }
```
