abstract class Moongoon::Collection::ReadOnly

Overview

A limited model class for interacting with a MongoDB collection.

NOTE Similar to Moongoon::Collection but can only be used to query a MongoDB collection.

class ReadOnly < Models::Collection::ReadOnly
  collection "my_models"

  property name : String?
  property age : Int32?
end

Included Modules

Defined in:

Constructors

Class Method Summary

Instance Method Summary

Macro Summary

Instance methods inherited from class Moongoon::MongoBase

_id : BSON::ObjectId? _id, _id! _id!, _id=(_id : BSON::ObjectId?) _id=, id id, id! id!, id=(id : String) id=, inserted? inserted?, persisted? persisted?, removed? : Bool removed?, unsets_to_bson : BSON? unsets_to_bson

Class methods inherited from class Moongoon::MongoBase

collection collection, database database, database_name database_name

Instance methods inherited from class Moongoon::Document

to_bson(bson = BSON.new) to_bson, to_tuple to_tuple

Constructor methods inherited from class Moongoon::Document

new(pull : JSON::PullParser)
new(bson : BSON)
new(**args : **T) forall T
new

Class methods inherited from class Moongoon::Document

from_bson(bson : BSON) from_bson

Constructor Detail

def self.find_by_id(id : BSON::ObjectId | String, query = BSON.new, order_by = {_id: -1}, fields = @@default_fields, **args) : self? #

Finds a single document by id and returns a Moongoon::Collection instance.

Syntax is similar to self.find_one.

user = User.find_by_id(123456)

def self.find_by_id!(id, **args) : self #

NOTE Similar to self.find_by_id, but raises when the document was not found.


def self.find_one(query = BSON.new, fields = @@default_fields, order_by = {_id: -1}, skip = 0, **args) : self? #

Finds a single document and returns a Moongoon::Collection instance.

# Retrieve a single user named Julien
user = User.find_one({ name: "Julien" })

The following optional arguments are available.

# Fetch only specific fields.
# Be extra careful to always fetch mandatory fields.
user = User.find_one({ name: "Julien" }, fields: { age: 1, name: 1 })

# Skip some results. Will return the 3rd user called Julien.
user = User.find_one({ name: "Julien"}, skip: 2)

NOTE Other arguments are available but will not be documented here. For more details check out the underlying cryomongo driver documentation and code.


def self.find_one!(query, **args) : self #

NOTE Similar to self.find_one, but raises when the document was not found.


def self.new(pull : JSON::PullParser) #

A limited model class for interacting with a MongoDB collection.

NOTE Similar to Moongoon::Collection but can only be used to query a MongoDB collection.

class ReadOnly < Models::Collection::ReadOnly
  collection "my_models"

  property name : String?
  property age : Int32?
end

Class Method Detail

def self.aggregation_pipeline(*args) #

Defines an aggregation pipeline that will be used instead of a plain find query.

If this macro is used, the model will always use the aggregate method to query documents and will use the stages passed as arguments to aggregate the results.

aggregation_pipeline(
  {
    "$addFields": {
      count: {
        "$size": "$array"
      }
    }
  },
  {
    "$project": {
      array: 0
    }
  }
)

def self.count(query = BSON.new, **args) : Int32 #

Counts the number of documents in the collection for a given query.

count = User.count({ name: "Julien" })

def self.default_fields(fields) #

Set the fields value to use by default when calling .find methods.

default_fields({ ignored_field: 0 })

def self.exist!(query = BSON.new, **args) : Bool #

Ensures that at least one document matches the query. Will raise when there is no match.

begin
  User.exist!({ name: "Julien" })
rescue e : Moongoon::Error::NotFound
  # No user named Julien found
end

def self.exist_by_id!(id, query = BSON.new, **args) : Bool #

Same as self.exist! but for a single document given its id.

begin
  User.exist_by_id!("123456")
rescue e : Moongoon::Error::NotFound
  # No user having _id "123456" found
end

def self.find(query = BSON.new, order_by = {_id: -1}, fields = @@default_fields, skip = 0, limit : Int? = nil, **args) : Array(self) #

Finds one or multiple documents and returns an array of Moongoon::Collection instances.

NOTE Documents are sorted by creation date in descending order.

# Search for persons named Julien
users = User.find({ name: "Julien" })

It is possible to use optional arguments to order, paginate and control queries.

# Order the results by birth_date
users = User.find({ name: "Julien" }, order_by: { birth: 1 })

# Paginate the results.
users = User.find({ name: "Julien" }, skip: 50, limit: 20)

# Fetch only specific fields.
# Be extra careful to always fetch mandatory fields.
users = User.find({ name: "Julien" }, fields: { age: 1, name: 1 })

NOTE Other arguments are available but will not be documented here. For more details check out the underlying cryomongo driver documentation and code.


def self.find!(query, **args) : Array(self) #

NOTE Similar to self.find, but raises when no documents are found.

begin
  users = User.find!({ name: "Julien" })
rescue
 raise "No one is named Julien."
end

def self.find_by_ids(ids, query = BSON.new, order_by = {_id: -1}, **args) : Array(self)? #

Finds one or multiple documents by their ids and returns an array of Moongoon::Collection instances.

Syntax is similar to self.find.

ids = ["1", "2", "3"]
users = User.find_by_ids(ids)

def self.find_by_ids!(ids, **args) : Array(self)? #

NOTE Similar to self.find_by_ids, but raises when no documents are found.


def self.find_ids(query = BSON.new, order_by = {_id: -1}, **args) : Array(String) #

Finds ids for documents matching the query argument and returns them an array of strings.

Syntax is similar to self.find.

jane_ids = User.find_ids({ name: "Jane" })

def self.index(keys : Hash(String, BSON::Value), collection : String? = nil, database : String? = nil, options = Hash(String, BSON::Value).new, name : String? = nil) : Nil #

Same as self.index but with hash arguments.

index ({ "a" => 1 }), name: "index_name", options: { "unique" => true }

def self.index(keys : NamedTuple, collection : String? = nil, database : String? = nil, options = NamedTuple.new, name : String? = nil) : Nil #

Defines an index that will be applied to this Model's underlying mongo collection.

Note that the order of fields do matter.

If not provided the driver will generate the name of the index from the keys names and order.

Please have a look at the MongoDB documentation for more details about index creation and the list of available index options.

# Specify one or more fields with a type (ascending or descending order, text indexing…)
index keys: { field1: 1, field2: -1 }
# Set the unique argument to create a unique index.
index keys: { field: 1 }, options: { unique: true }

Instance Method Detail

def fetch #

Returns a fresh copy of this object that is fetched from the database.

user = User.new(name: "John", age: 10)
User.update({ name: "John", age: 11 })
puts user.age
# => 10
puts user.fetch.age
# => 11

Macro Detail

macro reference(field, *, model, many = false, delete_cascade = false, clear_reference = false, back_reference = nil) #

References one or more documents belonging to another collection.

Creates a model field that will reference either one or multiple foreign documents depending on the arguments provided.

NOTE This macro is useful when using named arguments to keep the reference in sync when documents are added or removed from the other collection.

class MyModel < Moongoon::Collection
  # The following references are not kept in sync because extra named arguments are not used.

  # Reference a single user.
  reference user_id, model: User

  # References multiple users.
  reference user_ids, model: User, many: true

  reference user_ids, model: User, many: true
end

Named arguments

  • model: The referenced model class.
  • many: Set to true to reference multiple documents.
  • delete_cascade: If true, removes the referenced document(s) when this model is removed.
  • clear_reference: If true, sets the reference to nil (if referencing a single document), or removes the id from the reference array (if referencing multiple documents) when the referenced document(s) are removed.
  • back_reference: The name of the refence, if it exists, in the referenced model that back-references this model. If set, when a referenced document gets inserted, this reference will be updated to add the newly created id.
class MyModel < Moongoon::Collection
  # Now some examples that are using extra arguments.

  # References a single user from the User model class.
  # The user has a field that links to back to this model (best_friend_id).
  # Whenever a user is inserted, the reference will get updated to point to the linked user.
  reference user_id, model: User, back_reference: best_friend_id

  # References multiple pets. When this model is removed, all the pets
  # referenced will be removed as well.
  reference pet_ids, model: Pet, many: true, delete_cascade: true

  # Whenever a Pet is removed the reference will get updated and the
  # id of the Pet will be removed from the array.
  reference pet_id, model: Pet, many: true, clear_reference: true
end