mongoc

MongoDB C driver (libmongoc) bindings for Kit

Files

FileDescription
.editorconfigEditor formatting configuration
.gitignoreGit ignore rules for build artifacts and dependencies
.tool-versionsasdf tool versions (Zig, Kit)
LICENSEMIT license file
README.mdThis file
c/kit_mongoc.cC FFI wrapper around libmongoc and libbson
c/kit_mongoc.hC header for the FFI wrapper
examples/basic.kitBasic usage example
kit.tomlPackage manifest with metadata, native build settings, and tasks
src/mongoc.kitKit MongoDB API built on the C wrapper
tests/mongoc.test.kitTests for the Kit API surface

Dependencies

No Kit package dependencies.

This package requires the ffi capability and a system installation of the

MongoDB C driver. The current native build targets mongo-c-driver 2.x

pkg-config modules:

pkg-config --exists mongoc2 bson2

Installation

kit add gitlab.com/kit-lang/packages/kit-mongoc.git

System Requirements

PlatformCommand
macOSbrew install mongo-c-driver
Ubuntusudo apt install libmongoc-dev
Fedorasudo dnf install mongo-c-driver-devel

After installing the system package, verify that pkg-config can see the driver:

pkg-config --cflags --libs mongoc2 bson2

If kit install still reports that mongo-c-driver is missing, check that your

installed driver exposes the mongoc2 and bson2 pkg-config modules. Older

driver packages that only expose libmongoc-1.0 and libbson-1.0 are not

compatible with this package manifest.

Usage

import Kit.MongoC as Mongoc

main = fn =>
  Mongoc.init

  match Mongoc.client-new "mongodb://localhost:27017"
    | Err e -> println ("Connection error: " ++ e)
    | Ok client ->
      defer Mongoc.client-destroy client

      match Mongoc.ping client
        | Ok _ -> println "Connected to MongoDB"
        | Err e -> println ("Ping failed: " ++ e)

      match Mongoc.get-collection client "mydb" "users"
        | Err e -> println ("Collection error: " ++ e)
        | Ok coll ->
          defer Mongoc.collection-destroy coll

          match Mongoc.insert coll "{\"name\": \"Alice\", \"age\": 30}"
            | Ok _ -> println "Inserted"
            | Err e -> println ("Insert error: " ++ e)

          docs = Mongoc.find-all coll
          println ("All documents: " ++ docs)

          filtered = Mongoc.find coll "{\"age\": {\"$gt\": 25}}"
          println ("Filtered: " ++ filtered)

          match Mongoc.find-one coll "{\"name\": \"Alice\"}"
            | Some doc -> println ("Found: " ++ doc)
            | None -> println "Not found"

          match Mongoc.count coll
            | Ok n -> println ("Count: " ++ (show n))
            | Err e -> println ("Count error: " ++ e)

  Mongoc.cleanup

main

API Notes

Call Mongoc.init before using the driver and Mongoc.cleanup before process

exit. The C wrapper also lazy-initializes operations and defers global

libmongoc teardown until process exit, which keeps compiled Kit binaries from

using libmongoc after global driver cleanup.

Client, database, and collection handles are raw FFI pointers. Destroy handles

with the matching function when they are no longer needed:

HandleCleanup function
ClientMongoc.client-destroy
DatabaseMongoc.database-destroy
CollectionMongoc.collection-destroy

Documents and filters are passed as JSON strings. Find operations return JSON

strings generated by libbson's relaxed extended JSON format.

Most operations return Result ... String; Err contains the most recent

libmongoc/libbson error message from the C wrapper.

Development

Running Examples

Run examples with the interpreter:

kit run examples/basic.kit --allow=ffi

Compile examples to a native binary:

kit build examples/basic.kit --allow=ffi --output /tmp/kit-mongoc-basic
/tmp/kit-mongoc-basic

The basic example tries to connect to MongoDB on localhost:27017. A running

MongoDB server is useful for exercising successful CRUD operations, but the

example should still run and report connection or operation errors when no

server is available.

Running Tests

Run the test suite:

kit test

Run the test suite with coverage:

kit test --coverage

Running kit dev

Run the standard development workflow (format, check, test):

kit dev

This will:

  1. Build the native FFI library
  2. Format and check source files in src/
  3. Check examples in examples/
  4. Run tests in tests/ with coverage

Checking Interpreter/Compiler Parity

Run the package examples through both kit run and compiled execution:

kit parity --no-spinner --failures-only

This is useful for FFI packages because it catches output mismatches and native

runtime crashes that type checks do not cover.

Generating Documentation

Generate API documentation from doc comments:

kit doc

Note: Kit sources with doc comments (##) will generate HTML documents in docs/*.html

Cleaning Build Artifacts

Remove generated files, caches, and build artifacts:

kit task clean

Note: Defined in kit.toml.

Local Installation

To install this package locally for development:

kit install

This installs the package to ~/.kit/packages/@kit/mongoc/, builds

libkit_mongoc, and makes the package available for import as Kit.MongoC in

other projects.

Use verbose output when debugging native build or pkg-config issues:

kit install --verbose

License

This package is released under the MIT License - see LICENSE for details.

libmongoc is released under the Apache License 2.0.

Exported Functions & Types

init

Initialize the MongoDB driver. Must be called before any other operations.

Unit

cleanup

Clean up the MongoDB driver and release global resources.

Unit

client-new

Create a new MongoDB client from a connection URI.

Parameters:

Returns:

NonEmptyString -> Result Ptr String

client-destroy

Destroy a MongoDB client and free its resources.

Parameters:

    Ptr -> Unit

ping

Ping the MongoDB server to check connectivity.

Parameters:

Returns:

Ptr -> Result Unit String

get-database

Get a database handle.

Parameters:

Returns:

Ptr -> NonEmptyString -> Result Ptr String

database-destroy

Destroy a database handle.

Parameters:

    Ptr -> Unit

list-collections

List collection names in a database as a comma-separated string.

Parameters:

Returns:

Ptr -> String

get-collection

Get a collection handle.

Parameters:

Returns:

Ptr -> NonEmptyString -> NonEmptyString -> Result Ptr String

collection-destroy

Destroy a collection handle.

Parameters:

    Ptr -> Unit

count

Count documents in a collection.

Parameters:

Returns:

Ptr -> Result Int String

insert

Insert a JSON document into a collection.

Parameters:

Returns:

Ptr -> NonEmptyString -> Result Unit String

find

Find documents matching a filter. Returns a JSON array string.

Parameters:

Returns:

Ptr -> NonEmptyString -> String

find-all

Find all documents in a collection. Returns a JSON array string.

Parameters:

Returns:

Ptr -> String

find-one

Find a single document matching a filter. Returns a JSON string.

Parameters:

Returns:

Ptr -> NonEmptyString -> Option String

update-one

Update a single document matching a filter.

Parameters:

Returns:

Ptr -> NonEmptyString -> NonEmptyString -> Result Unit String

delete-one

Delete a single document matching a filter.

Parameters:

Returns:

Ptr -> NonEmptyString -> Result Unit String

delete-many

Delete all documents matching a filter.

Parameters:

Returns:

Ptr -> NonEmptyString -> Result Unit String

drop

Drop (delete) an entire collection.

Parameters:

Returns:

Ptr -> Result Unit String

create-index

Create an index on a collection.

Parameters:

Returns:

Ptr -> NonEmptyString -> Result Unit String