我正在使用 MongoDB C 库将文档插入到同一数据库中的各种集合中,并且在调用 BSON_APPEND_OID (doc, "_id", &oid);
我曾想跨集合使用相同的 oid——这样每个集合中的每个带时间戳的条目都将具有相同的 oid,这就是我开始收到错误的时候。所以我放弃了这一点,并尝试为每个条目创建新的 OID,但我仍然遇到同样的错误。
我尝试重用 OID 的版本一:
int insert_mongo(char json[100], char *coll, mongoc_client_t *client, bson_oid_t oid){
mongoc_collection_t *collection;
bson_error_t error;
bson_t *doc;
collection = mongoc_client_get_collection (client, "edison", coll);
doc = bson_new_from_json((const uint8_t *)json, -1, &error);
BSON_APPEND_OID (doc, "_id", &oid);
if (!doc) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
return EXIT_SUCCESS;
}
以及我创建新 OID 的版本 2:
int insert_mongo(char json[100], char *coll, mongoc_client_t *client){
mongoc_collection_t *collection;
bson_error_t error;
bson_t *doc;
bson_oid_t oid;
bson_oid_init (&oid, NULL);
collection = mongoc_client_get_collection (client, "edison", coll);
doc = bson_new_from_json((const uint8_t *)json, -1, &error);
BSON_APPEND_OID (doc, "_id", &oid);
if (!doc) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
if (!mongoc_collection_insert (collection, MONGOC_INSERT_NONE, doc, NULL, &error)) {
fprintf (stderr, "%s\n", error.message);
return EXIT_FAILURE;
}
bson_destroy (doc);
mongoc_collection_destroy (collection);
return EXIT_SUCCESS;
}
两个版本都在使用 MongoDB bson_append_oid() 调用函数的第二次错误:前提条件失败:bson