Search code examples
mongodbmongo-c-driver

How to get errors when calling mongoc_collection_find function?


Looking at the functions used in the Mongo C driver to do operations on collections, I see that many of them use a bson_error_t* return parameter to get possible errors (and they return false in that case).

For instance mongo_collection_insert:

bool

mongoc_collection_insert (mongoc_collection_t *collection,
                          mongoc_insert_flags_t flags,
                          const bson_t *document,
                          const mongoc_write_concern_t *write_concern,
                          bson_error_t *error);

Others (mongoc_collection_update or mongoc_collection_remove) work the same way.

However, the function to do queries (mongoc_collection_find) has the following signature:

mongoc_cursor_t *
mongoc_collection_find (mongoc_collection_t *collection,
                        mongoc_query_flags_t flags,
                        uint32_t skip,
                        uint32_t limit,
                        uint32_t batch_size,
                        const bson_t *query,
                        const bson_t *fields,
                        const mongoc_read_prefs_t *read_prefs)

There is not bson_error_t* parameter in this case, so how potential errors are returned?

I have thought that maybe checking for return value NULL-ness could mean error (although according to documentation return value is "A newly allocated mongoc_cursor_t that should be freed with mongoc_cursor_destroy() when no longer in use" and they don't mention the possibility of being NULL in case of fail) but even in that case, how to know which exact error has happened?


Solution

  • The operation mongoc_collection_aggregate is pretty similar to mongoc_collection_find and the documentation there says:

    This function returns a newly allocated mongoc_cursor_t that should be freed with mongoc_cursor_destroy() when no longer in use. The returned mongoc_cursor_t is never NULL; if the parameters are invalid, the bson_error_t in the mongoc_cursor_t is filled out, and the mongoc_cursor_t is returned before the server is selected. The user must call mongoc_cursor_next() on the returned mongoc_cursor_t to execute the aggregation pipeline.

    So maybe the problem is that mongoc_collection_find is incomplete but it works in the same way.

    I have proposed a modification to Mongo C driver documentation to confirm my hypothesis.