abstract class Moongoon::Collection

Overview

Base model class for interacting with a MongoDB collection.

This abstract class extends the Moongoon::Base class and enhances it with utility methods and macros used to query, update and configure an underlying MongoDB collection.

class MyModel < Moongoon::Collection
  collection "my_models"

  index keys: {name: 1}, options: {unique: true}

  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) #

Base model class for interacting with a MongoDB collection.

This abstract class extends the Moongoon::Base class and enhances it with utility methods and macros used to query, update and configure an underlying MongoDB collection.

class MyModel < Moongoon::Collection
  collection "my_models"

  index keys: {name: 1}, options: {unique: true}

  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.bulk_insert(self_array : Indexable(self), no_hooks = false, **args) : Indexable(self) #

Inserts multiple model instances in the database.

The _id field is generated during the insertion process.

john = User.new name: "John", age: 25
jane = User.new name: "Jane", age: 22
User.bulk_insert [john, jane]

def self.clear : Mongo::Commands::Common::DeleteResult? #

Clears the collection.

NOTE Use with caution!

Will remove all the documents in the collection.


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_and_modify(query, update, fields = @@default_fields, no_hooks = false, **args) #

Modifies and returns a single document.

See the official documentation.

User.find_and_modify({ name: "John" }, { "$set": { "name": "Igor" }})

def self.find_and_modify_by_id(id : BSON::ObjectId | String, update, query = BSON.new, no_hooks = false, **args) #

Modifies and returns a single document.

Similar to self.find_and_modify, except that a matching on the _id field will be added to the query argument.


def self.find_and_remove(query, fields = @@default_fields, no_hooks = false, **args) #

Removes and returns a single document.

See the official documentation.

User.find_and_remove({ name: "John" })

def self.find_and_remove_by_id(id, query = BSON.new, no_hooks = false, **args) #

Removes and returns a single document.

Similar to self.find_and_remove, except that a matching on the _id field will be added to the query argument.


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 }

def self.remove(query = BSON.new, no_hooks = false, **args) : Mongo::Commands::Common::DeleteResult? #

Removes one or more documents from the collection.

User.remove({ name: { "$in": ["John", "Jane"] }})

def self.remove_by_id(id, query = BSON.new, **args) : Mongo::Commands::Common::DeleteResult? #

Removes one document by id.

id = 123456
User.remove_by_id id

It is possible to add query filters to conditionally prevent removal.

# Remove the user only if he/she is named John
User.remove id, query: { name: "John" }

def self.remove_by_ids(ids, query = BSON.new, **args) : Mongo::Commands::Common::DeleteResult? #

Removes one or more documents from the collection by their ids.

ids = ["1", "2", "3"]
User.remove_by_ids ids

It is possible to add query filters to conditionally prevent removal.

# Remove the users only if they are named John
User.remove_by_ids ids , query: { name: "John" }

def self.update(query, update, no_hooks = false, **args) : Mongo::Commands::Common::UpdateResult? #

Updates one or more documents in the underlying collection.

Every document matching the query argument will be updated. See the MongoDB tutorial for more information about the syntax.

# Rename every person named "John" to "Igor".
User.update(query: { name: "John" }, update: { "$set": { name: "Igor" } })

def self.update_by_id(id : BSON::ObjectId | String, update, query = BSON.new, **args) : Mongo::Commands::Common::UpdateResult? #

Updates one document by id.

Similar to self.update, except that a matching on the _id field will be added to the query argument.

id = 123456
User.update_by_id(id, { "$set": { "name": "Igor" }})

It is possible to add query filters to conditionally prevent an update.

# Updates the user only if he/she is named John.
User.update_by_id(id, query: { name: "John" }, update: { "$set": { name: "Igor" }})

def self.update_by_ids(ids, update, query = BSON.new, **args) : Mongo::Commands::Common::UpdateResult? #

Updates one or multiple documents by their ids.

Similar to self.update, except that a matching on multiple _id fields will be added to the query argument.

ids = ["1", "2", "3"]
User.update_by_ids(ids, { "$set": { "name": "Igor" }})

It is possible to add query filters.

# Updates the users only if they are named John.
User.update_by_ids(ids, query: { name: "John" }, update: { "$set": { name: "Igor" }})

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

def insert(no_hooks = false, **args) : self #

Inserts this model instance in the database.

The _id field is generated during the insertion process.

user = User.new name: "John", age: 25
user.insert

def remove(query = BSON.new, no_hooks = false, **args) : Mongo::Commands::Common::DeleteResult? #

Removes one document having the same id as this model.

Matches on self.id.

user = User.find_by_id 123456
user.remove

It is possible to add query filters to conditionally prevent removal.

# Remove the user only if he/she is named John
user.remove({ name: "John" })

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

Updates a document having the same id as this model with the data stored in self.

Tries to match on self.id.

user = User.new name: "John", age: 25
user.insert
user.age = 26
user.update

It is possible to add query filters to conditionally prevent an update.

user = User.new name: "John", locked: true
user.insert
user.name = "Igor"
# Prevents updating users that are locked.
user.update({ locked: false })
pp User.find_by_id(user.id!).to_json
# => { "id": "some id", "name": "John", "locked": true }

The update can be restricted to specific fields.

user = User.new name: "John", age: 25
user.insert
user.age = 26
user.name = "Tom"
# Updates only the age field.
user.update(fields: {:age})

def update_fields(fields : F, **args) forall F #

Update specific fields both in the model and in database.

user = User.new name: "John", age: 25
user.insert
# Updates only the age field.
user.update({age: 26})

def update_query(query, fields = nil, no_hooks = false, **args) : self #

Updates one or more documents with the data stored in self.

Every document matching the query argument will be updated.

user = User.new name: "John", age: 25
user = User.new name: "Jane", age: 30
user.insert
user.age = 40
# Updates both documents
user.update_query({ name: {"$in": ["John", "Jane"]} })

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