API Reference

BSON

Mongoc.BSON — Type

A 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.0

C API

BSON is a wrapper for C struct bson_t.

source
Mongoc.BSONObjectId — Type

A 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;
source
Mongoc.BSONCode — Type

BSONCode is a BSON element with JavaScript source code.

Example

julia> bson = Mongoc.BSON("source" => Mongoc.BSONCode("function() = 1"))
BSON("{ "source" : { "$code" : "function() = 1" } }")
source
Mongoc.BSONUnsupported — Type

BSONUnsupported represents a type unsupported by this package. This includes BSONTYPEUNDEFINED which is deprecated and BSONTYPEREGEX which is not yet supported.

source
Mongoc.as_dict — Function
as_dict(document::BSON) :: Dict{String}

Converts a BSON document to a Julia Dict.

source
Mongoc.get_array — Function
get_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.

source
Mongoc.read_bson — Function
read_bson(io::IO) :: Vector{BSON}

Reads all BSON documents from io. This method will continue to read from io until it reaches eof.

source
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.

source
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.

source
read_bson(reader::BSONReader) :: Vector{BSON}

Reads all BSON documents from a reader.

source
Mongoc.write_bson — Function
write_bson(io::IO, bson::BSON;
    initial_buffer_capacity::Integer=DEFAULT_BSON_WRITER_BUFFER_CAPACITY)

Writes a single BSON document to io in binary format.

source
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)
end
source
Mongoc.read_next_bson — Function
read_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.

source
Mongoc.BSONError — Type

BSONError 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;
source
Mongoc.read_bson_from_json — Function
read_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" }
source

Client

Mongoc.Client — Type
Client(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")
source
Mongoc.set_appname! — Function
set_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

source
Mongoc.ping — Function
ping(client::Client) :: BSON

Pings 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 }")
source
Mongoc.find_databases — Function
find_databases(client::Client; options::Union{Nothing, BSON}=nothing) :: Cursor

Queries for databases.

source
Mongoc.has_database — Function
has_database(client::Client, database_name::String;
    options::Union{Nothing, BSON}=nothing) :: Bool

Helper method to check if there is a database named database_name.

See also Mongoc.find_databases.

source

ClientPool

Mongoc.ClientPool — Type
ClientPool(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)
source
Mongoc.set_max_size — Function
set_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)
source

Database

Mongoc.command_simple — Function
command_simple(database::Database, command::BSON) :: BSON
command_simple(collection::Collection, command::BSON) :: BSON

Executes 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

source
Mongoc.add_user — Function
add_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.

source
Mongoc.has_user — Function
has_user(database::Database, user_name::String) :: Bool

Checks if database has a user named user_name.

source
Mongoc.find_collections — Function
find_collections(database::Database; options::Union{Nothing, BSON}=nothing) :: Cursor

Queries for collections in a database.

source
Mongoc.read_command — Function
read_command(database::Database, command::BSON;
    options::Union{Nothing, BSON}=nothing) :: BSON

Issue a command with read semantics.

See https://mongoc.org/libmongoc/current/mongocdatabasereadcommandwith_opts.html.

source
Mongoc.write_command — Function
write_command(database::Database, command::BSON;
    options::Union{Nothing, BSON}=nothing) :: BSON

Issue a command with write semantics.

See https://mongoc.org/libmongoc/current/mongocdatabasereadwritecommandwithopts.html.

source

Collection

Mongoc.find — Function
find(collection::Collection, bson_filter::BSON=BSON();
    options::Union{Nothing, BSON}=nothing) :: Cursor

Executes 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
end

Check the libmongoc documentation for more information.

source
find(bucket::Bucket, bson_filter::BSON=BSON();
    options::BSON=BSON()) :: Cursor

Looks for files in GridFS bucket.

source
Mongoc.find_one — Function
find_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.

source
Mongoc.count_documents — Function
count_documents(collection::Collection, bson_filter::BSON=BSON();
    options::Union{Nothing, BSON}=nothing) :: Int

Returns 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))
source
Mongoc.drop — Function
drop(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.

source
Mongoc.find_and_modify — Function
find_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,
) :: BSON

Find documents and updates them in one go.

See Mongoc.FindAndModifyFlags for a list of accepted values for flags argument.

C API

source
Mongoc.FindAndModifyFlags — Type

Adds 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.

source
Mongoc.replace_one — Function
replace_one(
        collection::Collection,
        selector::BSON,
        replacement::BSON;
        options::Union{Nothing, BSON}=nothing
    )

Replace the result of querying by selector with replacement.

source
Mongoc.insert_many — Function
insert_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.

source
Mongoc.execute! — Function
execute!(bulk_operation::BulkOperation; reply=nothing) :: BulkOperationResult

Execute 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.

source

Aggregation

Mongoc.aggregate — Function
aggregate(collection::Collection, bson_pipeline::BSON;
    flags::QueryFlags=QUERY_FLAG_NONE,
    options::Union{Nothing, BSON}=nothing) :: Cursor

Use 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)
end

The result of the script above is:

BSON("{ "_id" : "B212", "total" : 200 }")
BSON("{ "_id" : "A123", "total" : 750 }")
source
Mongoc.QueryFlags — Type

QueryFlags 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).

source

Session

Mongoc.transaction — Function
transaction(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)
end
source

GridFS

Mongoc.MongoStreamFile — Type
MongoStreamFile(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.

source
Mongoc.upload — Function
upload(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.

source
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.

source
Mongoc.download — Function
download(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.

source
download(bucket::Bucket, remote_file, local_filepath::AbstractString;
    flags::Integer=(Base.Filesystem.JL_O_CREAT | Base.Filesystem.JL_O_RDWR), mode::Integer=0o600

Downloads 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.

source
Mongoc.delete — Function
delete(bucket::Bucket, file_id)
delete(bucket::Bucket, file_metadata::BSON)

Deletes a file from a GridFS Bucket.

source
Mongoc.open_download_stream — Function
open_download_stream(f, bucket, filename)
open_download_stream(bucket, filename) :: MongoIOStream

Opens 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)
end

Use 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)
end
source
Mongoc.open_upload_stream — Function
open_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]) :: MongoIOStream

Opens a stream to upload a file to a GridFS Bucket.

file_info is a BSON document with the following fields:

  • _id as an optional identifier.

  • filename as 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)
source