Class: Mongo::DBRef

Inherits:
Object
  • Object
show all
Includes:
BSON::JSON
Defined in:
lib/mongo/dbref.rb

Overview

Represents a DBRef document in the database.

Since:

  • 2.1.0

Defined Under Namespace

Modules: ClassMethods

Constant Summary

COLLECTION =

The constant for the collection reference field.

Since:

  • 2.1.0

'$ref'.freeze
ID =

The constant for the id field.

Since:

  • 2.1.0

'$id'.freeze
DATABASE =

The constant for the database field.

Since:

  • 2.1.0

'$db'.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection, id, database = nil) ⇒ DBRef

Instantiate a new DBRef.

Examples:

Create the DBRef.

Mongo::DBRef.new('users', id, 'database')

Parameters:

  • collection (String)

    The collection name.

  • id (BSON::ObjectId)

    The object id.

  • database (String) (defaults to: nil)

    The database name.

Since:

  • 2.1.0



71
72
73
74
75
# File 'lib/mongo/dbref.rb', line 71

def initialize(collection, id, database = nil)
  @collection = collection
  @id = id
  @database = database
end

Instance Attribute Details

#collectionString (readonly)

Returns collection The collection name.

Returns:

  • (String)

    collection The collection name.

Since:

  • 2.1.0



39
40
41
# File 'lib/mongo/dbref.rb', line 39

def collection
  @collection
end

#databaseString (readonly)

Returns database The database name.

Returns:

  • (String)

    database The database name.

Since:

  • 2.1.0



45
46
47
# File 'lib/mongo/dbref.rb', line 45

def database
  @database
end

#idBSON::ObjectId (readonly)

Returns id The referenced document id.

Returns:

  • (BSON::ObjectId)

    id The referenced document id.

Since:

  • 2.1.0



42
43
44
# File 'lib/mongo/dbref.rb', line 42

def id
  @id
end

Instance Method Details

#as_json(*args) ⇒ Hash

Get the DBRef as a JSON document

Examples:

Get the DBRef as a JSON hash.

dbref.as_json

Returns:

  • (Hash)

    The max key as a JSON hash.

Since:

  • 2.1.0



55
56
57
58
59
# File 'lib/mongo/dbref.rb', line 55

def as_json(*args)
  document = { COLLECTION => collection, ID => id }
  document.merge!(DATABASE => database) if database
  document
end

#to_bson(buffer = BSON::ByteBuffer.new, validating_keys = BSON::Config.validating_keys?) ⇒ String

Converts the DBRef to raw BSON.

Examples:

Convert the DBRef to raw BSON.

dbref.to_bson

Parameters:

  • buffer (BSON::ByteBuffer) (defaults to: BSON::ByteBuffer.new)

    The encoded BSON buffer to append to.

  • validating_keys (true, false) (defaults to: BSON::Config.validating_keys?)

    Whether keys should be validated when serializing.

Returns:

  • (String)

    The raw BSON.

Since:

  • 2.1.0



88
89
90
# File 'lib/mongo/dbref.rb', line 88

def to_bson(buffer = BSON::ByteBuffer.new, validating_keys = BSON::Config.validating_keys?)
  as_json.to_bson(buffer)
end