mongodb-driver v0.5.1 Mongo View Source

The main entry point for doing queries. All functions take a topology to run the query on.

Generic options

All operations take these options.

  • :timeout - The maximum time that the caller is allowed the to hold the connection’s state (ignored when using a run/transaction connection, default: 15_000)
  • :pool - The pooling behaviour module to use, this option is required unless the default DBConnection.Connection pool is used
  • :pool_timeout - The maximum time to wait for a reply when making a synchronous call to the pool (default: 5_000)
  • :queue - Whether to block waiting in an internal queue for the connection's state (boolean, default: true)
  • :log - A function to log information about a call, either a 1-arity fun, {module, function, args} with DBConnection.LogEntry.t prepended to args or nil. See DBConnection.LogEntry (default: nil)
  • :database - the database to run the operation on
  • :connect_timeout - maximum timeout for connect (default: 5_000)

Read options

All read operations that returns a cursor take the following options for controlling the behaviour of the cursor.

  • :batch_size - Number of documents to fetch in each batch
  • :limit - Maximum number of documents to fetch with the cursor
  • :read_preference - specifies the rules for selecting a server to query

Write options

All write operations take the following options for controlling the write concern.

  • :w - The number of servers to replicate to before returning from write operators, a 0 value will return immediately, :majority will wait until the operation propagates to a majority of members in the replica set (Default: 1)
  • :j If true, the write operation will only return after it has been committed to journal - (Default: false)
  • :wtimeout - If the write concern is not satisfied in the specified interval, the operation returns an error

Link to this section Summary

Functions

Performs aggregation operation using the aggregation pipeline.

Issue a database command. If the command has parameters use a keyword list for the document because the "command key" has to be the first in the document.

Similar to command/3 but unwraps the result and raises on error.

Returns the count of documents that would match a find/4 query.

Similar to count_documents/4 but unwraps the result and raises on error.

Remove all documents matching the filter from the collection.

Similar to delete_many/4 but unwraps the result and raises on error.

Remove a document matching the filter from the collection.

Similar to delete_one/4 but unwraps the result and raises on error.

Finds the distinct values for a specified field across a collection.

Similar to distinct/5 but unwraps the result and raises on error.

Estimate the number of documents in a collection using collection metadata.

Similar to estimated_document_count/3 but unwraps the result and raises on error.

Selects documents in a collection and returns a cursor for the selected documents.

Selects a single document in a collection and returns either a document or nil.

Finds a document and updates it (using atomic modifiers).

Insert multiple documents into the collection.

Similar to insert_many/4 but unwraps the result and raises on error.

Insert a single document into the collection.

Similar to insert_one/4 but unwraps the result and raises on error.

Convenient function that returns a cursor with the names of the indexes.

Returns a cursor to enumerate all indexes

Generates a new BSON.ObjectId.

Sends a ping command to the server.

Replace a single document matching the filter with the new document.

Similar to replace_one/5 but unwraps the result and raises on error.

Determines the appropriate connection depending on the type (:read, :write). The result is   a tuple with the connection, slave_ok flag and mongos flag. Possibly you have to set slave_ok == true in the options for the following request because you are requesting a secondary server.

Start and link to a database connection process.

Converts the DataTime to a MongoDB timestamp.

Update all documents matching the filter.

Similar to update_many/5 but unwraps the result and raises on error.

Update a single document matching the filter.

Similar to update_one/5 but unwraps the result and raises on error.

Creates a change stream cursor all collections of the database.

Returns the current wire version.

Link to this section Types

Link to this type

collection() View Source
collection() :: String.t()

Link to this type

conn() View Source
conn() :: DbConnection.Conn

Link to this type

initial_type() View Source
initial_type() :: :unknown | :single | :replica_set_no_primary | :sharded

Link to this type

result(t) View Source
result(t) :: :ok | {:ok, t} | {:error, Mongo.Error.t()}

Link to this type

result!(t) View Source
result!(t) :: nil | t | no_return()

Link to this section Functions

Link to this function

aggregate(topology_pid, coll, pipeline, opts \\ []) View Source

Performs aggregation operation using the aggregation pipeline.

For all options see Options

Link to this function

child_spec(opts, child_opts \\ []) View Source

Link to this function

command(topology_pid, query, opts \\ []) View Source

Issue a database command. If the command has parameters use a keyword list for the document because the "command key" has to be the first in the document.

Link to this function

command!(topology_pid, query, opts \\ []) View Source

Similar to command/3 but unwraps the result and raises on error.

Link to this function

count_documents(topology_pid, coll, filter, opts \\ []) View Source

Returns the count of documents that would match a find/4 query.

Options

  • :limit - Maximum number of documents to fetch with the cursor
  • :skip - Number of documents to skip before returning the first
Link to this function

count_documents!(topology_pid, coll, filter, opts \\ []) View Source

Similar to count_documents/4 but unwraps the result and raises on error.

Link to this function

delete_many(topology_pid, coll, filter, opts \\ []) View Source

Remove all documents matching the filter from the collection.

Link to this function

delete_many!(topology_pid, coll, filter, opts \\ []) View Source

Similar to delete_many/4 but unwraps the result and raises on error.

Link to this function

delete_one(topology_pid, coll, filter, opts \\ []) View Source

Remove a document matching the filter from the collection.

Link to this function

delete_one!(topology_pid, coll, filter, opts \\ []) View Source

Similar to delete_one/4 but unwraps the result and raises on error.

Link to this function

distinct(topology_pid, coll, field, filter, opts \\ []) View Source

Finds the distinct values for a specified field across a collection.

Options

  • :max_time - Specifies a time limit in milliseconds
  • :collation - Optionally specifies a collation to use in MongoDB 3.4 and
Link to this function

distinct!(topology_pid, coll, field, filter, opts \\ []) View Source

Similar to distinct/5 but unwraps the result and raises on error.

Link to this function

estimated_document_count(topology_pid, coll, opts) View Source
estimated_document_count(GenServer.server(), collection(), Keyword.t()) ::
  result(non_neg_integer())

Estimate the number of documents in a collection using collection metadata.

Link to this function

estimated_document_count!(topology_pid, coll, opts) View Source
estimated_document_count!(GenServer.server(), collection(), Keyword.t()) ::
  result!(non_neg_integer())

Similar to estimated_document_count/3 but unwraps the result and raises on error.

Link to this function

find(topology_pid, coll, filter, opts \\ []) View Source

Selects documents in a collection and returns a cursor for the selected documents.

For all options see Options

Use the underscore style, for example to set the option singleBatch use single_batch. Another example:

 Mongo.find(top, "jobs", %{}, batch_size: 2)
Link to this function

find_one(conn, coll, filter, opts \\ []) View Source

Selects a single document in a collection and returns either a document or nil.

If multiple documents satisfy the query, this method returns the first document according to the natural order which reflects the order of documents on the disk.

For all options see Options

Use the underscore style, for example to set the option readConcern use read_concern. Another example:

 Mongo.find_one(top, "jobs", %{}, read_concern: %{level: "local"})
Link to this function

find_one_and_delete(topology_pid, coll, filter, opts \\ []) View Source
find_one_and_delete(
  GenServer.server(),
  collection(),
  BSON.document(),
  Keyword.t()
) :: result(BSON.document())

Finds a document and deletes it.

Options

  • :max_time - The maximum amount of time to allow the query to run (in MS)
  • :projection - Limits the fields to return for all matching documents.
  • :sort - Determines which document the operation modifies if the query selects multiple documents.
  • :collation - Optionally specifies a collation to use in MongoDB 3.4 and higher.
Link to this function

find_one_and_replace(topology_pid, coll, filter, replacement, opts \\ []) View Source

Finds a document and replaces it.

Options

  • :bypass_document_validation - Allows the write to opt-out of document level validation
  • :max_time - The maximum amount of time to allow the query to run (in MS)
  • :projection - Limits the fields to return for all matching documents.
  • :return_document - Returns the replaced or inserted document rather than the original. Values are :before or :after. (default is :before)
  • :sort - Determines which document the operation modifies if the query selects multiple documents.
  • :upsert - Create a document if no document matches the query or updates the document.
  • :collation - Optionally specifies a collation to use in MongoDB 3.4 and higher.
Link to this function

find_one_and_update(topology_pid, coll, filter, update, opts \\ []) View Source
find_one_and_update(
  GenServer.server(),
  collection(),
  BSON.document(),
  BSON.document(),
  Keyword.t()
) :: result(BSON.document()) | {:ok, nil}

Finds a document and updates it (using atomic modifiers).

Options

  • :bypass_document_validation - Allows the write to opt-out of document level validation
  • :max_time - The maximum amount of time to allow the query to run (in MS)
  • :projection - Limits the fields to return for all matching documents.
  • :return_document - Returns the replaced or inserted document rather than the original. Values are :before or :after. (default is :before)
  • :sort - Determines which document the operation modifies if the query selects multiple documents.
  • :upsert - Create a document if no document matches the query or updates the document.
  • :collation - Optionally specifies a collation to use in MongoDB 3.4 and
Link to this function

insert_many(topology_pid, coll, docs, opts \\ []) View Source

Insert multiple documents into the collection.

If any of the documents is missing the _id field or it is nil, an ObjectId will be generated, and insertd into the document. Ids of all documents will be returned in the result struct.

Options

For more information about options see Options

Examples

Mongo.insert_many(pid, "users", [%{first_name: "John", last_name: "Smith"}, %{first_name: "Jane", last_name: "Doe"}])
Link to this function

insert_many!(topology_pid, coll, docs, opts \\ []) View Source

Similar to insert_many/4 but unwraps the result and raises on error.

Link to this function

insert_one(topology_pid, coll, doc, opts \\ []) View Source

Insert a single document into the collection.

If the document is missing the _id field or it is nil, an ObjectId will be generated, inserted into the document, and returned in the result struct.

Examples

Mongo.insert_one(pid, "users", %{first_name: "John", last_name: "Smith"})
Link to this function

insert_one!(topology_pid, coll, doc, opts \\ []) View Source

Similar to insert_one/4 but unwraps the result and raises on error.

Link to this function

list_index_names(topology_pid, coll, opts \\ []) View Source
list_index_names(GenServer.server(), String.t(), Keyword.t()) :: %Stream{
  accs: term(),
  done: term(),
  enum: term(),
  funs: term()
}

Convenient function that returns a cursor with the names of the indexes.

Link to this function

list_indexes(topology_pid, coll, opts \\ []) View Source
list_indexes(GenServer.server(), String.t(), Keyword.t()) :: cursor()

Returns a cursor to enumerate all indexes

Generates a new BSON.ObjectId.

Sends a ping command to the server.

Link to this function

replace_one(topology_pid, coll, filter, replacement, opts \\ []) View Source

Replace a single document matching the filter with the new document.

Options

  • :upsert - if set to true creates a new document when no document matches the filter (default: false)
Link to this function

replace_one!(topology_pid, coll, filter, replacement, opts \\ []) View Source

Similar to replace_one/5 but unwraps the result and raises on error.

Link to this function

select_server(topology_pid, type, opts \\ []) View Source

Determines the appropriate connection depending on the type (:read, :write). The result is   a tuple with the connection, slave_ok flag and mongos flag. Possibly you have to set slave_ok == true in the options for the following request because you are requesting a secondary server.

Link to this function

show_collections(topology_pid, opts \\ []) View Source
show_collections(GenServer.server(), Keyword.t()) :: cursor()

Getting Collection Names

Link to this function

start_link(opts) View Source
start_link(Keyword.t()) :: {:ok, pid()} | {:error, Mongo.Error.t() | atom()}

Start and link to a database connection process.

Options

  • :database - The database to use (required)
  • :hostname - The host to connect to (require)
  • :port - The port to connect to your server (default: 27017)
  • :url - A mongo connection url. Can be used in place of :hostname and :database (optional)
  • :seeds - A list of host names in the cluster. Can be used in place of :hostname (optional)
  • :username - The User to connect with (optional)
  • :password - The password to connect with (optional)
  • :auth - List of additional users to authenticate as a keyword list with :username and :password keys (optional)
  • :auth_source - The database to authenticate against
  • :set_name - The name of the replica set to connect to (required if connecting to a replica set)
  • :type - a hint of the topology type. See initial_type/0 for valid values (default: :unknown)
  • :idle - The idle strategy, :passive to avoid checkin when idle and :active to checking when idle (default: :passive)
  • :idle_timeout - The idle timeout to ping the database (default: 1_000)
  • :connect_timeout - The maximum timeout for the initial connection (default: 5_000)
  • :backoff_min - The minimum backoff interval (default: 1_000)
  • :backoff_max - The maximum backoff interval (default: 30_000)
  • :backoff_type - The backoff strategy, :stop for no backoff and to stop, :exp of exponential, :rand for random and :ran_exp for random exponential (default: :rand_exp)
  • :after_connect - A function to run on connect use run/3. Either a 1-arity fun, {module, function, args} with DBConnection.t, prepended to args or nil (default: nil)
  • :auth_mechanism - options for the mongo authentication mechanism, currently only supports :x509 atom as a value
  • :ssl - Set to true if ssl should be used (default: false)
  • :ssl_opts - A list of ssl options, see the ssl docs

Error Reasons

  • :single_topology_multiple_hosts - A topology of :single was set but multiple hosts were given
  • :set_name_bad_topology - A :set_name was given but the topology was set to something other than :replica_set_no_primary or :single

Converts the DataTime to a MongoDB timestamp.

Link to this function

update_many(topology_pid, coll, filter, update, opts \\ []) View Source

Update all documents matching the filter.

Uses MongoDB update operators to specify the updates. For more information and all options please refer to the MongoDB documentation

Link to this function

update_many!(topology_pid, coll, filter, update, opts \\ []) View Source

Similar to update_many/5 but unwraps the result and raises on error.

Link to this function

update_one(topology_pid, coll, filter, update, opts \\ []) View Source

Update a single document matching the filter.

Uses MongoDB update operators to specify the updates. For more information please refer to the MongoDB documentation

Example:

Mongo.update_one(MongoPool,
  "my_test_collection",
  %{"filter_field": "filter_value"},
  %{"$set": %{"modified_field": "new_value"}})

Options

  • :upsert - if set to true creates a new document when no document matches the filter (default: false)
Link to this function

update_one!(topology_pid, coll, filter, update, opts \\ []) View Source

Similar to update_one/5 but unwraps the result and raises on error.

Link to this function

watch_collection(topology_pid, coll, pipeline, on_resume_token \\ nil, opts \\ []) View Source
watch_collection(
  GenServer.server(),
  collection(),
  [BSON.document()],
  (... -> any()),
  Keyword.it()
) :: cursor()

Creates a change stream cursor on collections.

on_resume_token is function that takes the new resume token, if it changed.

Options

  • :full_document -
  • :max_time - Specifies a time limit in milliseconds. This option is used on getMore commands
  • :batch_size - Specifies the number of maximum number of documents to return (default: 1)
  • :resume_after - Specifies the logical starting point for the new change stream.
  • :start_at_operation_time - The change stream will only provide changes that occurred at or after the specified timestamp (since 4.0)
  • :start_after - Similar to resumeAfter, this option takes a resume token and starts a new change stream returning the first notification after the token. This will allow users to watch collections that have been dropped and recreated or newly renamed collections without missing any notifications. (since 4.0.7)
Link to this function

watch_db(topology_pid, pipeline, on_resume_token \\ nil, opts \\ []) View Source
watch_db(GenServer.server(), [BSON.document()], (... -> any()), Keyword.it()) ::
  cursor()

Creates a change stream cursor all collections of the database.

on_resume_token is function that takes the new resume token, if it changed.

Options

  • :full_document -
  • :max_time - Specifies a time limit in milliseconds. This option is used on getMore commands
  • :batch_size - Specifies the number of maximum number of documents to return (default: 1)
  • :resume_after - Specifies the logical starting point for the new change stream.
  • :start_at_operation_time - The change stream will only provide changes that occurred at or after the specified timestamp (since 4.0)
  • :start_after - Similar to resumeAfter, this option takes a resume token and starts a new change stream returning the first notification after the token. This will allow users to watch collections that have been dropped and recreated or newly renamed collections without missing any notifications. (since 4.0.7)
Link to this function

wire_version(conn, opts \\ []) View Source

Returns the current wire version.