API Reference
BSON
Mongoc.BSON
— Type.A BSON
represents a document in Binary JSON format, defined at http://bsonspec.org/.
In Julia, you can manipulate a BSON
instance just like a Dict
.
Example
bson = Mongoc.BSON()
bson["name"] = "my name"
bson["num"] = 10.0
C API
BSON
is a wrapper for C struct bson_t
.
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;
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" } }")
Mongoc.as_json
— Function.as_json(bson::BSON; canonical::Bool=false) :: String
Converts 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
— Function.as_dict(document::BSON) :: Dict
Converts a BSON document to a Julia Dict
.
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.
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
— 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.
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
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.
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;
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")
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
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 }")
Mongoc.get_server_mongodb_version
— Function.get_server_mongodb_version(client::Client) :: VersionNumber
Queries the version for the MongoDB server instance.
Mongoc.find_databases
— Function.find_databases(client::Client; options::Union{Nothing, BSON}=nothing) :: Cursor
Queries for databases.
Mongoc.get_database_names
— Function.get_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
— 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
.
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)
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)
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
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.
Mongoc.remove_user
— Function.remove_user(database::Database, username::String)
Removes a user from database.
Mongoc.has_user
— Function.has_user(database::Database, user_name::String) :: Bool
Checks if database
has a user named user_name
.
Mongoc.find_collections
— Function.find_collections(database::Database; options::Union{Nothing, BSON}=nothing) :: Cursor
Queries for collections in a database
.
Mongoc.get_collection_names
— Function.get_collection_names(database::Database;
options::Union{Nothing, BSON}=nothing) :: Vector{String}
Helper method to get collection names.
See also Mongoc.find_collections
.
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.
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.
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))
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.
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
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.
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 }")
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).
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