API Reference
BSON
Mongoc.BSON — TypeA BSON represents a document in Binary JSON format, defined at https://bsonspec.org/. Dictionary inputs, including nested dictionaries, are encoded in iteration order.
Indexing reads decoded values. Assignment appends a field, even when its key already exists. Embedded documents and arrays are decoded into independent Julia containers; mutating them does not update the original BSON. To change these values, modify a dictionary returned by as_dict and construct a new BSON from it. This requires values supported by the constructor; duplicate keys collapse and binary subtype information may be lost.
Example
bson = Mongoc.BSON()
bson["name"] = "my name"
bson["num"] = 10.0C API
BSON is a wrapper for C struct bson_t.
Mongoc.BSONObjectId — TypeA BSONObjectId represents a unique identifier for a BSON document.
Example
The following generates a new BSONObjectId.
julia> Mongoc.BSONObjectId()C API
BSONObjectId instances addresses are passed to libbson/libmongoc API using Ref(oid), and are owned by the Julia process.
Mirrors C struct bson_oid_t:
typedef struct {
uint8_t bytes[12];
} bson_oid_t;Mongoc.BSONCode — TypeBSONCode is a BSON element with JavaScript source code.
Example
julia> bson = Mongoc.BSON("source" => Mongoc.BSONCode("function() = 1"))
BSON("{ "source" : { "$code" : "function() = 1" } }")Mongoc.BSONTimestamp — TypeBSONTimestamp is a special internal type used by MongoDB replication and sharding.
Mongoc.BSONUnsupported — TypeBSONUnsupported represents a type unsupported by this package. This includes BSONTYPEUNDEFINED which is deprecated and BSONTYPEREGEX which is not yet supported.
Mongoc.as_json — Functionas_json(bson::BSON; canonical::Bool=false) :: StringConverts a bson object to a JSON string.
Example
julia> document = Mongoc.BSON("{ "hey" : 1 }")
BSON("{ "hey" : 1 }")
julia> Mongoc.as_json(document)
"{ "hey" : 1 }"
julia> Mongoc.as_json(document, canonical=true)
"{ "hey" : { "$numberInt" : "1" } }"C API
Mongoc.as_dict — Functionas_dict(document::BSON) :: Dict{String}Converts a BSON document to a Julia Dict.
Mongoc.get_array — Functionget_array(doc::BSON, key::AbstractString, ::Type{T})Get an array from the document with a specified type T. This allows obtaining a type-stable return value. Note that if an array element cannot be converted to the specified type, an error will be thrown.
Mongoc.read_bson — Functionread_bson(io::IO) :: Vector{BSON}Reads all BSON documents from io. This method will continue to read from io until it reaches eof.
read_bson(data::Vector{UInt8}) :: Vector{BSON}Parses a vector of bytes to a vector of BSON documents. Useful when reading BSON as binary from a stream.
read_bson(filepath::AbstractString) :: Vector{BSON}Reads all BSON documents from a file located at filepath.
This will open a Mongoc.BSONReader pointing to the file and will parse file contents to BSON documents.
read_bson(reader::BSONReader) :: Vector{BSON}Reads all BSON documents from a reader.
Mongoc.write_bson — Functionwrite_bson(io::IO, bson::BSON;
initial_buffer_capacity::Integer=DEFAULT_BSON_WRITER_BUFFER_CAPACITY)Writes a single BSON document to io in binary format.
write_bson(io::IO, bson_list::Vector{BSON};
initial_buffer_capacity::Integer=DEFAULT_BSON_WRITER_BUFFER_CAPACITY)Writes a vector of BSON documents to io in binary format.
Example
list = Vector{Mongoc.BSON}()
let
src = Mongoc.BSON()
src["id"] = 1
src["name"] = "1st"
push!(list, src)
end
let
src = Mongoc.BSON()
src["id"] = 2
src["name"] = "2nd"
push!(list, src)
end
open("documents.bson", "w") do io
Mongoc.write_bson(io, list)
endMongoc.read_next_bson — Functionread_next_bson(reader::BSONReader) :: Union{Nothing, BSON}Reads the next BSON document available in the stream pointed by reader. Returns nothing if reached the end of the stream.
Mongoc.BSONError — TypeBSONError is the default Exception for BSON/MongoDB function call errors.
C API
Mirrors C struct bson_error_t.
BSONError instances addresses are passed to libbson/libmongoc API using Ref(error), and are owned by the Julia process.
typedef struct {
uint32_t domain;
uint32_t code;
char message[504];
} bson_error_t;Mongoc.BSONValue — TypeWrapper for bsonvaluet.
Mongoc.get_as_bson_value — Functionget_as_bson_value(doc, key) :: BSONValueReturns a value stored in a bson document doc as a BSONValue.
See also Mongoc.BSONValue.
Mongoc.read_bson_from_json — Functionread_bson_from_json(filepath::AbstractString) :: Vector{BSON}Reads a JSON file into a list of BSON documents. The file should contain a sequence of valid JSON documents.
Example of a valid JSON file
{ "num" : 1, "str" : "two" }
{ "num" : 2, "str" : "three" }Client
Mongoc.Client — TypeClient(host, port)
Client(uri)
Client()
Client(pool; [try_pop=false])Creates a Client, which represents a connection to a MongoDB database.
See also Mongoc.ClientPool.
Examples:
These lines are equivalent.
c = Mongoc.Client()
c = Mongoc.Client("localhost", 27017)
c = Mongoc.Client("mongodb://localhost:27017")Mongoc.set_appname! — Functionset_appname!(client::Client, appname::String)Sets the application name for this client.
This string, along with other internal driver details, is sent to the server as part of the initial connection handshake.
C API
Mongoc.ping — Functionping(client::Client) :: BSONPings the server, testing wether it is reachable.
One thing to keep in mind is that operations on MongoDB are lazy, which means that a client reaches a server only when it needs to transfer documents.
Example
julia> client = Mongoc.Client() # nothing happens here between client and server
Client(URI("mongodb://localhost:27017"))
julia> Mongoc.ping(client) # connection to server happens here
BSON("{ "ok" : 1.0 }")Mongoc.get_server_mongodb_version — Functionget_server_mongodb_version(client::Client) :: VersionNumberQueries the version for the MongoDB server instance.
Mongoc.find_databases — Functionfind_databases(client::Client; options::Union{Nothing, BSON}=nothing) :: CursorQueries for databases.
Mongoc.get_database_names — Functionget_database_names(client::Client; options::Union{Nothing, BSON}=nothing) :: Vector{String}Helper method to get a list of names for all databases.
See also Mongoc.find_databases.
Mongoc.has_database — Functionhas_database(client::Client, database_name::String;
options::Union{Nothing, BSON}=nothing) :: BoolHelper method to check if there is a database named database_name.
See also Mongoc.find_databases.
ClientPool
Mongoc.ClientPool — TypeClientPool(uri; [max_size])Creates a pool of connections to a MongoDB instance.
Example
const REPLICA_SET_URL = "mongodb://127.0.0.1:27021,127.0.0.1:27022,127.0.0.1:27023/?replicaSet=rs0"
pool = Mongoc.ClientPool(REPLICA_SET_URL, max_size=2)
# create Clients from a pool
client1 = Mongoc.Client(pool)
client2 = Mongoc.Client(pool)When you reach the maximum number of clients, the next call to Mongoc.Client(pool) will block until a Client is released.
Use try_pop=true option to throw an error instead of blocking the current thread:
# will throw `AssertionError`
client3 = Mongoc.Client(pool, try_pop=true)Mongoc.set_max_size — Functionset_max_size(pool, max_size)Set the maximum number of clients on the client pool.
Example
const REPLICA_SET_URL = "mongodb://127.0.0.1:27021,127.0.0.1:27022,127.0.0.1:27023/?replicaSet=rs0"
pool = Mongoc.ClientPool(REPLICA_SET_URL)
Mongoc.set_max_size(pool, 4)Database
Mongoc.command_simple — Functioncommand_simple(database::Database, command::BSON) :: BSON
command_simple(collection::Collection, command::BSON) :: BSONExecutes a command given by a JSON string or a BSON instance.
It returns the first document from the result cursor.
Example
julia> client = Mongoc.Client() # connects to localhost at port 27017
Client(URI("mongodb://localhost:27017"))
julia> bson_result = Mongoc.command_simple(client["admin"], "{ "ping" : 1 }")
BSON("{ "ok" : 1.0 }")C API
Mongoc.add_user — Functionadd_user(database::Database, username::String, password::String, roles::Union{Nothing, BSON},
custom_data::Union{Nothing, BSON}=nothing)This function shall create a new user with access to database.
Warning: Do not call this function without TLS.
Mongoc.remove_user — Functionremove_user(database::Database, username::String)Removes a user from database.
Mongoc.has_user — Functionhas_user(database::Database, user_name::String) :: BoolChecks if database has a user named user_name.
Mongoc.find_collections — Functionfind_collections(database::Database; options::Union{Nothing, BSON}=nothing) :: CursorQueries for collections in a database.
Mongoc.get_collection_names — Functionget_collection_names(database::Database;
options::Union{Nothing, BSON}=nothing) :: Vector{String}Helper method to get collection names.
See also Mongoc.find_collections.
Mongoc.read_command — Functionread_command(database::Database, command::BSON;
options::Union{Nothing, BSON}=nothing) :: BSONIssue a command with read semantics.
See https://mongoc.org/libmongoc/current/mongocdatabasereadcommandwith_opts.html.
Mongoc.write_command — Functionwrite_command(database::Database, command::BSON;
options::Union{Nothing, BSON}=nothing) :: BSONIssue a command with write semantics.
See https://mongoc.org/libmongoc/current/mongocdatabasereadwritecommandwithopts.html.
Collection
Mongoc.find — Functionfind(collection::Collection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: CursorExecutes a query on collection and returns an iterable Cursor.
Example
function find_contract_codes(collection, criteria::Dict=Dict()) :: Vector{String}
result = Vector{String}()
let
bson_filter = Mongoc.BSON(criteria)
bson_options = Mongoc.BSON("""{ "projection" : { "_id" : true }, "sort" : { "_id" : 1 } }""")
for bson_document in Mongoc.find(collection, bson_filter, options=bson_options)
push!(result, bson_document["_id"])
end
end
return result
endCheck the libmongoc documentation for more information.
find(bucket::Bucket, bson_filter::BSON=BSON();
options::BSON=BSON()) :: CursorLooks for files in GridFS bucket.
Mongoc.find_one — Functionfind_one(collection::Collection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: Union{Nothing, BSON}Execute a query to a collection and returns the first element of the result set.
Returns nothing if the result set is empty.
Mongoc.count_documents — Functioncount_documents(collection::Collection, bson_filter::BSON=BSON();
options::Union{Nothing, BSON}=nothing) :: IntReturns the number of documents on a collection, with an optional filter given by bson_filter.
length(collection) and Mongoc.count_documents(collection) produces the same output.
Example
result = length(collection, Mongoc.BSON("_id" => oid))Mongoc.drop — Functiondrop(database::Database, opts::Union{Nothing, BSON}=nothing)
drop(collection::Collection, opts::Union{Nothing, BSON}=nothing)Drops database or collection.
For information about opts argument, check the libmongoc documentation for database drop or collection drop.
Mongoc.find_and_modify — Functionfind_and_modify(collection::Collection, query::BSON;
update::Union{Nothing, BSON}=nothing,
sort::Union{Nothing, BSON}=nothing,
fields::Union{Nothing, BSON}=nothing,
flags::Union{Nothing, FindAndModifyFlags}=nothing,
bypass_document_validation::Bool=false,
) :: BSONFind documents and updates them in one go.
See Mongoc.FindAndModifyFlags for a list of accepted values for flags argument.
C API
Mongoc.FindAndModifyFlags — TypeAdds one or more flags to the FindAndModifyOptsBuilder. These flags can be ORed together, as in flags = Mongoc.FIND_AND_MODIFY_FLAG_UPSERT | Mongoc.FIND_AND_MODIFY_FLAG_RETURN_NEW.
FIND_AND_MODIFY_FLAG_NONE: Default. Doesn’t add anything to the builder.FIND_AND_MODIFY_FLAG_REMOVE: Will instruct findandmodify to remove the matching document.FIND_AND_MODIFY_FLAG_UPSERT: Update the matching document or, if no document matches, insert the document.FIND_AND_MODIFY_FLAG_RETURN_NEW: Return the resulting document.
Mongoc.find_one_and_delete — Functionfind_one_and_delete(collection::Collection, bson_filter::BSON;
options::Union{Nothing, BSON}=nothing
) :: Union{Nothing, BSON}Delete a document and return it.
See db.collection.findOneAndDelete for a list of accepted options.
Mongoc.find_one_and_replace — Functionfind_one_and_replace(collection::Collection, bson_filter::BSON, bson_replacement::BSON;
options::Union{Nothing, BSON}=nothing
) :: Union{Nothing, BSON}Replace a document and return the original.
See db.collection.findOneAndReplace for a list of accepted options.
Mongoc.find_one_and_update — Functionfind_one_and_update(collection::Collection, bson_filter::BSON, bson_update::BSON;
options::Union{Nothing, BSON}=nothing
) :: Union{Nothing, BSON}Update a document and return the original.
See db.collection.findOneAndUpdate for a list of accepted options.
Mongoc.replace_one — Functionreplace_one(
collection::Collection,
selector::BSON,
replacement::BSON;
options::Union{Nothing, BSON}=nothing
)Replace the result of querying by selector with replacement.
Mongoc.insert_many — Functioninsert_many(collection, documents::Vector{BSON};
bulk_options=nothing, insert_options=nothing, reply=nothing)Insert documents into a Collection or CollectionSession, returning a BulkOperationResult. With bulk_options=BSON("ordered" => false), the server continues after individual write errors, but this function still throws BSONError if any write fails.
Pass reply=Ref{BSON}() to retain the bulk reply when execution throws. The reply contains counts and writeErrors when available; error indices are zero-based positions in documents. Setup errors before bulk execution leave the reference unchanged. See execute! for the reply's lifetime and success behavior.
Mongoc.execute! — Functionexecute!(bulk_operation::BulkOperation; reply=nothing) :: BulkOperationResultExecute a bulk operation once and release its native handle, including on failure. Errors throw BSONError even when some writes succeeded.
Pass reply=Ref{BSON}() to retain the driver's reply on success or failure. The reference is assigned after the driver returns, before checking for an error. It remains unchanged if execution is rejected before calling the driver. A reply may be empty on failure; it does not by itself indicate success. On success, reply[] is the same document as the returned result's reply field. The reply remains usable after the bulk operation's native handle is released.
Aggregation
Mongoc.aggregate — Functionaggregate(collection::Collection, bson_pipeline::BSON;
flags::QueryFlags=QUERY_FLAG_NONE,
options::Union{Nothing, BSON}=nothing) :: CursorUse Mongoc.aggregate to execute an aggregation command.
Example
The following reproduces the example from the MongoDB Tutorial.
docs = [
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 500, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 250, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "B212", "amount" : 200, "status" : "A" }"""),
Mongoc.BSON("""{ "cust_id" : "A123", "amount" : 300, "status" : "D" }""")
]
collection = client["my-database"]["aggregation-collection"]
append!(collection, docs)
# Sets the pipeline command
bson_pipeline = Mongoc.BSON("""
[
{ "$match" : { "status" : "A" } },
{ "$group" : { "_id" : "$cust_id", "total" : { "$sum" : "$amount" } } }
]
""")
for doc in Mongoc.aggregate(collection, bson_pipeline)
println(doc)
endThe result of the script above is:
BSON("{ "_id" : "B212", "total" : 200 }")
BSON("{ "_id" : "A123", "total" : 750 }")Mongoc.QueryFlags — TypeQueryFlags correspond to the MongoDB wire protocol. They may be bitwise or’d together. They may modify how a query is performed in the MongoDB server.
These flags are passed as optional argument for the aggregation function Mongoc.aggregate.
This data type mirrors C struct mongoc_query_flags_t. See libmongoc docs for more information.
Constants
Mongoc.QUERY_FLAG_NONE: Specify no query flags.
Mongoc.QUERY_FLAG_TAILABLE_CURSOR: Cursor will not be closed when the last data is retrieved. You can resume this cursor later.
Mongoc.QUERY_FLAG_SLAVE_OK: Allow query of replica set secondaries.
Mongoc.QUERY_FLAG_OPLOG_REPLAY: Used internally by MongoDB.
Mongoc.QUERY_FLAG_NO_CURSOR_TIMEOUT: The server normally times out an idle cursor after an inactivity period (10 minutes). This prevents that.
Mongoc.QUERY_FLAG_AWAIT_DATA: Use with Mongoc.MONGOC_QUERY_TAILABLE_CURSOR. Block rather than returning no data. After a period, time out.
Mongoc.QUERY_FLAG_EXHAUST: Stream the data down full blast in multiple "reply" packets. Faster when you are pulling down a lot of data and you know you want to retrieve it all.
Mongoc.QUERY_FLAG_PARTIAL: Get partial results from mongos if some shards are down (instead of throwing an error).
Session
Mongoc.transaction — Functiontransaction(f::Function, client::Client; session_options::SessionOptions=SessionOptions())Use do-syntax to execute a transaction.
Transaction will be commited automatically. If an error occurs, the transaction is aborted.
The session parameter should be treated the same way as a Client: from a session you get a database, and a collection that are bound to the session.
Mongoc.transaction(client) do session
database = session["my_database"]
collection = database["my_collection"]
new_item = Mongoc.BSON()
new_item["inserted"] = true
push!(collection, new_item)
endGridFS
Mongoc.AbstractMongoStream — TypeInterface
Mutable fields
handle::Ptr{Cvoid}isopen::Booltimeout_msec::Intchunk_size::UInt
Mongoc.MongoStreamFile — TypeMongoStreamFile(filepath;
[flags=JL_O_RDONLY], [mode=0],
[timeout_msec=DEFAULT_TIMEOUT_MSEC],
[chunk_size=DEFAULT_CHUNK_SIZE])Creates a stream from file located at filepath.
flags is the input to pass to open. Must be one of the constants defined at Base.Filesystem: Base.Filesystem.JL_O_RDONLY, Base.Filesystem.JL_O_CREAT, etc.
mode is an optional mode to pass to open.
Mongoc.upload — Functionupload(bucket::Bucket, filename::AbstractString, source::AbstractMongoStream;
options::Union{Nothing, BSON}=nothing,
file_id=BSONObjectId())Uploads data from source to a GridFS file filename.
bson_file_id is a BSON document with a _id field. If _id field is not present, a BSONObjectId will be generated.
upload(bucket::Bucket, remote_filename::AbstractString, local_source_filepath::AbstractString;
options::Union{Nothing, BSON}=nothing,
file_id=BSONObjectId())High-level interface to upload a local file to a GridFS bucket.
Mongoc.download — Functiondownload(bucket::Bucket, file_id, target::AbstractMongoStream)Download a GridFS file identified by file_id to target stream.
file_id may be either a BSONValue or a BSON document with an _id field.
download(bucket::Bucket, remote_file, local_filepath::AbstractString;
flags::Integer=(Base.Filesystem.JL_O_CREAT | Base.Filesystem.JL_O_RDWR), mode::Integer=0o600Downloads a GridFS file remote_file to local_filepath.
remote_file can be either a unique filename, or a file_id::BSONValue, or file_info::BSON.
Mongoc.delete — Functiondelete(bucket::Bucket, file_id)
delete(bucket::Bucket, file_metadata::BSON)Deletes a file from a GridFS Bucket.
Mongoc.open_download_stream — Functionopen_download_stream(f, bucket, filename)
open_download_stream(bucket, filename) :: MongoIOStreamOpens a stream for reading a remote file identified by filename.
Example
Open a stream, do some work, then close it.
io = Mongoc.open_download_stream(bucket, file)
try
tmp_str = read(io, String)
finally
close(io)
endUse do-syntax to ensure that the io stream will be closed in case something goes wrong.
Mongoc.open_download_stream(bucket, remote_filename) do io
tmp_str = read(io, String)
endMongoc.open_upload_stream — Functionopen_upload_stream(bucket, file_id, filename; [options], [timeout_msec], [chunk_size]) :: MongoIOStream
open_upload_stream(bucket, filename; [options], [timeout_msec], [chunk_size]) :: MongoIOStream
open_upload_stream(bucket, file_info; [options], [timeout_msec], [chunk_size]) :: MongoIOStreamOpens a stream to upload a file to a GridFS Bucket.
file_info is a BSON document with the following fields:
_idas an optional identifier.filenameas the name of the file in the remote bucket.
If _id is not provided, a BSONObjectId will be generated.
Example
data = rand(UInt8, 3_000_000)
remote_filename = "uploaded.data"
io = Mongoc.open_upload_stream(bucket, remote_filename)
write(io, data)
close(io)Mongoc.abort_upload — Functionabort_upload(io::MongoIOStream)Aborts the upload of a GridFS upload stream.