mongoc_cursor_t(3) Client-side cursor abtraction


typedef struct _mongoc_cursor_t mongoc_cursor_t;

mongoc_cursor_t provides access to a MongoDB query cursor. It wraps up the wire protocol negotiation required to initiate a query and retrieve an unknown number of documents.

Cursors are lazy, meaning that no network traffic occurs until the first call to mongoc_cursor_next(3) \&.

At that point we can:

Determine which host we've connected to with mongoc_cursor_get_host(3) \&.
Retrieve more records with repeated calls to mongoc_cursor_next(3) \&.
Test for more records with mongoc_cursor_more(3)
Clone a query to repeat execution at a later point with mongoc_cursor_clone(3) \&.
Test for errors with mongoc_cursor_error(3) \&.


mongoc_cursor_t is NOT thread safe. It may only be used from the thread it was created from.


/* gcc example.c -o example $(pkg-config --cflags --libs libmongoc-1.0) */
/* ./example-client [CONNECTION_STRING [COLLECTION_NAME]] */
#include <mongoc.h>
#include <stdio.h>
#include <stdlib.h>
main (int   argc,
      char *argv[])
   mongoc_client_t *client;
   mongoc_collection_t *collection;
   mongoc_cursor_t *cursor;
   bson_error_t error;
   const bson_t *doc;
   const char *uristr = "mongodb://";
   const char *collection_name = "test";
   bson_t query;
   char *str;
   mongoc_init ();
   if (argc > 1) {
      uristr = argv [1];
   if (argc > 2) {
      collection_name = argv [2];
   client = mongoc_client_new (uristr);
   if (!client) {
      fprintf (stderr, "Failed to parse URI.\n");
      return EXIT_FAILURE;
   bson_init (&query);
#if 0
   bson_append_utf8 (&query, "hello", -1, "world", -1);
   collection = mongoc_client_get_collection (client, "test", collection_name);
   cursor = mongoc_collection_find (collection,
                                    NULL,  /* Fields, NULL for all. */
                                    NULL); /* Read Prefs, NULL for default */
   while (mongoc_cursor_next (cursor, &doc)) {
      str = bson_as_json (doc, NULL);
      fprintf (stdout, "%s\n", str);
      bson_free (str);
   if (mongoc_cursor_error (cursor, &error)) {
      fprintf (stderr, "Cursor Failure: %s\n", error.message);
      return EXIT_FAILURE;
   bson_destroy (&query);
   mongoc_cursor_destroy (cursor);
   mongoc_collection_destroy (collection);
   mongoc_client_destroy (client);
   mongoc_cleanup ();
   return EXIT_SUCCESS;


This page is part of MongoDB C Driver. Please report any bugs at