Mongo (Mongodb v1.0.0) 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:5_000
):pool
- The pooling behaviour module to use, this option is required unless the defaultDBConnection.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}
withDBConnection.LogEntry.t
prepended toargs
ornil
. SeeDBConnection.LogEntry
(default:nil
):database
- the database to run the operation on:connect_timeout_ms
- 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.
Creates one or more indexes
for the specified collection coll
.
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.
Drops the specified index
name in the collection coll
.
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 deletes it.
Finds a document and replaces it.
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.
Convenience function returning a cursor with the names of the indexes.
Returns a cursor to enumerate all indexes.
Generates a new BSON.ObjectId
.
Replace a single document matching the filter with the new document.
Similar to replace_one/5
but unwraps the result and raises on error.
Lists collection names
Start and link to a database connection process.
Start new session for given topology_pid
.
Performs one or more update operations.
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.
Link to this section Types
Specs
collection() :: String.t()
Specs
conn() :: DbConnection.Conn
Specs
cursor()
Specs
initial_type() :: :unknown | :single | :replica_set_no_primary | :sharded
Specs
result(t) :: :ok | {:ok, t} | {:error, Mongo.Error.t()}
Specs
result!(t) :: nil | t | no_return()
Specs
write_result(t) :: :ok | {:ok, t} | {:error, Mongo.Error.t()} | {:error, Mongo.WriteError.t()}
Link to this section Functions
Specs
aggregate(GenServer.server(), collection(), [BSON.document()], Keyword.t()) :: cursor()
Performs aggregation operation using the aggregation pipeline.
Options
:allow_disk_use
- Enables writing to temporary files (Default: false):collation
- Optionally specifies a collation to use in MongoDB 3.4 and:max_time
- Specifies a time limit in milliseconds:use_cursor
- Use a cursor for a batched response (Default: true)
Specs
command(GenServer.server(), BSON.document(), Keyword.t()) :: result(BSON.document())
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.
Specs
command!(GenServer.server(), BSON.document(), Keyword.t()) :: result!(BSON.document())
Similar to command/3
but unwraps the result and raises on error.
Specs
count_documents(GenServer.server(), collection(), BSON.document(), Keyword.t()) :: result(non_neg_integer())
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
Specs
count_documents!(GenServer.server(), collection(), BSON.document(), Keyword.t()) :: result!(non_neg_integer())
Similar to count_documents/4
but unwraps the result and raises on error.
Specs
create_indexes(GenServer.server(), String.t(), [Keyword.t()], Keyword.t()) :: result(Mongo.CreateIndexesResult.t())
Creates one or more indexes
for the specified collection coll
.
See
https://docs.mongodb.com/manual/reference/method/db.collection.createIndexes/#mongodb-method-db.collection.createIndexes
for the syntax of indexes
.
Specs
delete_many(GenServer.server(), collection(), BSON.document(), Keyword.t()) :: write_result(Mongo.DeleteResult.t())
Remove all documents matching the filter from the collection.
Specs
delete_many!(GenServer.server(), collection(), BSON.document(), Keyword.t()) :: result!(Mongo.DeleteResult.t())
Similar to delete_many/4
but unwraps the result and raises on error.
Specs
delete_one(GenServer.server(), collection(), BSON.document(), Keyword.t()) :: write_result(Mongo.DeleteResult.t())
Remove a document matching the filter from the collection.
Specs
delete_one!(GenServer.server(), collection(), BSON.document(), Keyword.t()) :: result!(Mongo.DeleteResult.t())
Similar to delete_one/4
but unwraps the result and raises on error.
Specs
distinct( GenServer.server(), collection(), String.t() | atom(), BSON.document(), Keyword.t() ) :: result([BSON.t()])
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
Specs
distinct!( GenServer.server(), collection(), String.t() | atom(), BSON.document(), Keyword.t() ) :: result!([BSON.t()])
Similar to distinct/5
but unwraps the result and raises on error.
Specs
drop_index( GenServer.server(), String.t(), String.t() | [String.t()], Keyword.t() ) :: result(Mongo.DropIndexResult.t())
Drops the specified index
name in the collection coll
.
To drop multiple indexes at once pass a list of indexes to index
. To drop all indexes except
that of _id
pass "*" to index
.
See https://docs.mongodb.com/manual/reference/command/dropIndexes/#dropindexes
Specs
estimated_document_count(GenServer.server(), collection(), Keyword.t()) :: result(non_neg_integer())
Estimate the number of documents in a collection using collection metadata.
Specs
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.
Specs
find(GenServer.server(), collection(), BSON.document(), Keyword.t()) :: cursor()
Selects documents in a collection and returns a cursor for the selected documents.
Options
:comment
- Associates a comment to a query:cursor_type
- Set to :tailable or :tailable_await to return a tailable cursor:max_time
- Specifies a time limit in milliseconds:modifiers
- Meta-operators modifying the output or behavior of a query, see http://docs.mongodb.org/manual/reference/operator/query-modifier/:cursor_timeout
- Set to false if cursor should not close after 10 minutes (Default: true):sort
- Sorts the results of a query in ascending or descending order:projection
- Limits the fields to return for all matching document:skip
- The number of documents to skip before returning (Default: 0)
Specs
find_one(GenServer.server(), collection(), BSON.document(), Keyword.t()) :: BSON.document() | nil
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.
Options
:comment
- Associates a comment to a query:cursor_type
- Set to :tailable or :tailable_await to return a tailable cursor:max_time
- Specifies a time limit in milliseconds:modifiers
- Meta-operators modifying the output or behavior of a query, see http://docs.mongodb.org/manual/reference/operator/query-modifier/:cursor_timeout
- Set to false if cursor should not close after 10 minutes (Default: true):projection
- Limits the fields to return for all matching document:skip
- The number of documents to skip before returning (Default: 0)
Specs
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.
find_one_and_replace(topology_pid, coll, filter, replacement, opts \\ [])
View SourceSpecs
find_one_and_replace( GenServer.server(), collection(), BSON.document(), BSON.document(), Keyword.t() ) :: result(BSON.document())
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.
find_one_and_update(topology_pid, coll, filter, update, opts \\ [])
View SourceSpecs
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
Specs
insert_many(GenServer.server(), collection(), [BSON.document()], Keyword.t()) :: write_result(Mongo.InsertManyResult.t())
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
:continue_on_error
- even if insert fails for one of the documents continue inserting the remaining ones (default:false
):ordered
- A boolean specifying whether the mongod instance should perform an ordered or unordered insert. (default:true
)
Examples
Mongo.insert_many(pid, "users", [%{first_name: "John", last_name: "Smith"}, %{first_name: "Jane", last_name: "Doe"}])
Specs
insert_many!(GenServer.server(), collection(), [BSON.document()], Keyword.t()) :: result!(Mongo.InsertManyResult.t())
Similar to insert_many/4
but unwraps the result and raises on error.
Specs
insert_one(GenServer.server(), collection(), BSON.document(), Keyword.t()) :: write_result(Mongo.InsertOneResult.t())
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"})
Specs
insert_one!(GenServer.server(), collection(), BSON.document(), Keyword.t()) :: result!(Mongo.InsertOneResult.t())
Similar to insert_one/4
but unwraps the result and raises on error.
Specs
list_index_names(GenServer.server(), String.t(), Keyword.t()) :: %Stream{ accs: term(), done: term(), enum: term(), funs: term() }
Convenience function returning a cursor with the names of the indexes.
Specs
list_indexes(GenServer.server(), String.t(), Keyword.t()) :: cursor()
Returns a cursor to enumerate all indexes.
Specs
object_id() :: BSON.ObjectId.t()
Generates a new BSON.ObjectId
.
Specs
replace_one( GenServer.server(), collection(), BSON.document(), BSON.document(), Keyword.t() ) :: write_result(Mongo.UpdateResult.t())
Replace a single document matching the filter with the new document.
Options
:upsert
- if set totrue
creates a new document when no document matches the filter (default:false
)
Specs
replace_one!( GenServer.server(), collection(), BSON.document(), BSON.document(), Keyword.t() ) :: result!(Mongo.UpdateResult.t())
Similar to replace_one/5
but unwraps the result and raises on error.
Specs
show_collections(GenServer.server(), Keyword.t()) :: cursor()
Lists collection names
Specs
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:socket_dir
- Connect to MongoDB via UNIX sockets in the given directory. The socket name is derived based on the port. This is the preferred method for configuring sockets and it takes precedence over the hostname. If you are connecting to a socket outside of the MongoDB convection, use:socket
instead.:socket
- Connect to MongoDB via UNIX sockets in the given path. This option takes precedence over:hostname
and:socket_dir
.: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. Seeinitial_type/0
for valid values (default::unknown
):pool
- The pool module to use, seeDBConnection
for pool dependent options, this option must be included with all requests contacting the pool if notDBConnection.Connection
(default:DBConnection.Connection
):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_ms
- 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 userun/3
. Either a 1-arity fun,{module, function, args}
withDBConnection.t
, prepended toargs
ornil
(default:nil
):auth_mechanism
- options for the mongo authentication mechanism, currently only supports:x509
atom as a value:ssl
- Set totrue
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
Specs
start_session(GenServer.server(), keyword()) :: {:ok, Mongo.Session.session()} | {:error, term()}
Start new session for given topology_pid
.
Options
:causal_consistency
- whether the causal consistency should be persisted within session. Default totrue
.:read_concern
- what should be the level for read consistency in session. Should be map with value:level
that is one of the described in Read Concern documentation. Applied only when:casual_consistency
is set totrue
. Bu default uses cluster configuration.:retry_writes
- whether retryable faliures should be retried. Defaults totrue
.
:causal_consistency
can be set only during the session creation, but the :read_concern
can be set for each transaction independently.
Performs one or more update operations.
This function is especially useful for more complex update operations (e.g. upserting multiple documents). For more straightforward use cases you may prefer to use these higher level APIs:
update_one/5
update_one!/5
update_many/5
update_many!5
Each update in updates
may be specified using either the short-hand
Mongo-style syntax (in reference to their docs) or using a long-hand, Elixir
friendly syntax.
See https://docs.mongodb.com/manual/reference/command/update/#update-statements
e.g. long-hand query
becomes short-hand q
, snake case array_filters
becomes arrayFilters
Specs
update_many( GenServer.server(), collection(), BSON.document(), BSON.document(), Keyword.t() ) :: write_result(Mongo.UpdateResult.t())
Update all documents matching the filter.
Uses MongoDB update operators to specify the updates. For more information please refer to the MongoDB documentation
Options
:upsert
- if set totrue
creates a new document when no document matches the filter (default:false
)
Specs
update_many!( GenServer.server(), collection(), BSON.document(), BSON.document(), Keyword.t() ) :: result!(Mongo.UpdateResult.t())
Similar to update_many/5
but unwraps the result and raises on error.
Specs
update_one( GenServer.server(), collection(), BSON.document(), BSON.document(), Keyword.t() ) :: write_result(Mongo.UpdateResult.t())
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 totrue
creates a new document when no document matches the filter (default:false
)
Specs
update_one!( GenServer.server(), collection(), BSON.document(), BSON.document(), Keyword.t() ) :: result!(Mongo.UpdateResult.t())
Similar to update_one/5
but unwraps the result and raises on error.
Specs
with_session(GenServer.server(), keyword(), (Mongo.Session.session() -> return)) :: return when return: term()