cmongodbmongo-c-driver

Mongo C Driver accessing a document by its _id


How can I access a document in a Mongo database using only its _id, with mongo-c-driver? I want to define a function

void *get_doc_by_id(int obj_id) {
    // return document if exists
} 

Solution

  • First off, keep in mind that an int is not guaranteed to be large enough to hold a MongoDB object id (and in all cases I know of, is not). MongoDB object ids are 96-bit in size and int is typically 32-bits in size.

    You might try something like:

    /**
     * get_doc_by_id:
     * @conn: A mongo connection.
     * @db_and_collection: The "db.collection" namespace.
     * @oid: A bson_oid_t containing the document id.
     *
     * Fetches a document by the _id field.
     *
     * Returns: A new bson* that should be freed with bson_destroy() if
     *    successful; otherwise NULL on failure.
     */
    bson *
    get_doc_by_id (mongo            *conn,
                   const char       *db_and_collection,
                   const bson_oid_t *oid)
    {
        bson query;
        bson *ret = NULL;
        mongo_cursor *cursor;
    
        assert(conn);
        assert(db_and_collection);
        assert(oid);
    
        bson_init(&query);
        bson_append_oid(&query, "_id", oid);
    
        cursor = mongo_find(conn, db_and_collection, &query, NULL, 1, 0, 0);
        if (!cursor) {
            goto cleanup;
        }
    
        if (mongoc_cursor_next(cursor) != MONGO_OK) {
            goto cleanup;
        }
    
        ret = calloc(1, sizeof *ret);
        if (!ret) {
            goto cleanup;
        }
    
        bson_copy(ret, mongoc_cursor_bson(cursor));
    
    cleanup:
        if (cursor) {
            mongo_cursor_destroy(cursor);
        }
        bson_destroy(&query);
    
        return ret;
    }