# man > BSON::DBRef

---
type: CommandReference
command: BSON::DBRef
mode: perldoc
section: 3pm
source: perldoc
---

## Quick Reference
- `bson_dbref( $oid, $collection_name )` — create a DBRef object
- `$dbref->id` — get the referenced document’s `_id` (BSON::OID)
- `$dbref->ref` — get the collection name
- `$dbref->db` — get the database name (optional, discouraged)
- `$dbref->TO_JSON()` — serialize to extended JSON when `BSON_EXTJSON` is true

## Name
BSON type wrapper for MongoDB DBRefs

## Synopsis
perl
use BSON::Types ':all';
my $dbref = bson_dbref( $oid, $collection_name, { extra => { ... } } );
## Attributes
- `id` — **Required.** The `_id` value of the referenced document. Must be a [BSON::OID](https://metacpan.org/pod/BSON::OID) object if the `_id` is an ObjectID.
- `ref` — **Required.** The referenced collection name or [MongoDB::Collection](https://metacpan.org/pod/MongoDB::Collection) object (coerced to string). Can also be specified as `'$ref'` in the constructor.
- `db` — **Optional.** The database name or [MongoDB::Database](https://metacpan.org/pod/MongoDB::Database) object. Not recommended; supported for round‑tripping only. Can also be specified as `'$db'`.
- `extra` — **Optional.** A hash reference of additional fields. Do **not** rely on this field for new DBRefs; exists solely for round‑tripping with drivers that support extra fields.

## Methods
- `TO_JSON()` — If the module variable `$BSON::Types::BSON_EXTJSON` is true, returns a hashref compatible with MongoDB’s [Extended JSON](https://github.com/mongodb/specifications/blob/master/source/extended-json.rst) format: `{ '$ref' => '<collection>', '$id' => '<id>' }`. If false, throws an error because the DBRef cannot otherwise be represented in JSON.

## Examples
perl
use BSON::Types ':all';

# Create a DBRef pointing to an OID in the 'users' collection
my $oid   = BSON::OID->new;
my $dbref = bson_dbref( $oid, 'users' );

print $dbref->id,  "\n";   # prints the OID hex string
print $dbref->ref, "\n";   # 'users'

# Serialize to extended JSON
local $BSON::Types::BSON_EXTJSON = 1;
my $extjson = $dbref->TO_JSON;   # { '$ref' => 'users', '$id' => $oid }
## See Also
- [BSON::Types](https://metacpan.org/pod/BSON::Types)
- [BSON::OID](https://metacpan.org/pod/BSON::OID)
- [MongoDB::Collection](https://metacpan.org/pod/MongoDB::Collection)
- [MongoDB::Database](https://metacpan.org/pod/MongoDB::Database)
- [MongoDB Database References](https://docs.mongodb.com/manual/reference/database-references/)
- [Extended JSON Specification](https://github.com/mongodb/specifications/blob/master/source/extended-json.rst)