Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongo C驱动程序通过文档的\u id访问文档_C_Mongodb_Mongo C Driver - Fatal编程技术网

Mongo C驱动程序通过文档的\u id访问文档

Mongo C驱动程序通过文档的\u id访问文档,c,mongodb,mongo-c-driver,C,Mongodb,Mongo C Driver,如何使用Mongo-c-driver仅使用其_id访问Mongo数据库中的文档?我想定义一个函数 void *get_doc_by_id(int obj_id) { // return document if exists } 首先,请记住,int不能保证足够大以容纳MongoDB对象id(据我所知,在所有情况下都不能)。MongoDB对象ID的大小为96位,int的大小通常为32位 您可以尝试以下方法: /** * get_doc_by_id: * @conn: A mongo

如何使用Mongo-c-driver仅使用其_id访问Mongo数据库中的文档?我想定义一个函数

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

首先,请记住,int不能保证足够大以容纳MongoDB对象id(据我所知,在所有情况下都不能)。MongoDB对象ID的大小为96位,int的大小通常为32位

您可以尝试以下方法:

/**
 * 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;
}
替代解决方案: ( 选定参数:

const mongoc_collection_t *col;
const bson_oid_t          *oid;
)


你听过教程了吗?(特别是
查询
部分?
bson\u append\u oid
bson\u append\u int
mongoc_cursor_t *cursor = NULL;
bson_error_t    *err = NULL;
std::string      oid_str;
bson_t          *qry = bson_new();
std::string      query;

bson_oid_to_string(oid, oid_str);
query = "{\"_id\":{\"$oid\":\"" + oid_str + "\"}}";
bson_init_from_json(qry, query.c_str(), -1, err);
cursor = mongoc_collection_find(col, MONGOC_QUERY_NONE,
                                0, 0, 0, qry, NULL, NULL);