> 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/tham-chieu-database-trong-mongodb/su-dung-dbrefs-trong-mongodb.md).

# Sử dụng DBRefs trong MongoDB

Có 3 trường trong DBRefs:

**$ref:** Trường này xác định Collection của Document được tham chiếu.

**$id:** Trường này xác định trường \_id của Document được tham chiếu.

**$db:** Trường này là một trường tùy ý, chứa tên của Database mà Document được tham chiếu ở trong đó.

Giả sử một user document có trường **address** dạng DBRefs như sau:

```javascript
{

    "_id": ObjectId("53402597d852426020000002"),

    "address": {

        "$ref": "address_home",

        "$id": ObjectId("534009e4d852427820000002"),

        "$db": "tutorialspoint"
    },

    "contact": "987654321",

    "dob": "01-01-1991",

    "name": "Tom Benzamin"

}
```

Trường address dạng DBRefs ở đây xác định rằng **address** document được tham chiếu ở trong **address\_home** collection dưới tutorialspoint database và có một id là: 534009e4d852427820000002.

Phần code sau sẽ nhìn vào Collection được xác định bởi tham số **$ref** (là address\_home trong trường hợp này) cho một Document với id được xác định bởi tham số **$id** trong DBRefs.

```
>var user = db.users.findOne({"name":"Tom Benzamin"})

>var dbRef = user.address

>db[dbRef.$ref].findOne({"_id":(dbRef.$id)})
```

Code trên trả về address document sau đây, mà có mặt trong **address\_home** collection:

```javascript
{

    "_id" : ObjectId("534009e4d852427820000002"),

    "building" : "22 A, Indiana Apt",

    "pincode" : 123456,

    "city" : "Los Angeles",

    "state" : "California"

}
```
