Mongo:将 JSON 转换为 BSON 时出错

Mongo: Error converting JSON to BSON

我正在尝试使用 Mongo C 驱动程序将以下 MongoDB JSON 命令转换为有效的 BSON:

db.test.update({
   "_id" : ObjectId("5624200d4bacd3940b8b2d62"),
  "folders.folder_id": "3_root",
  "folders.files": { $elemMatch: { "file": "5BD252AD-10C9-4DCE-A59C-5E3223BDDC60"}} },
  {$inc : { "folders.0.files.$.favorites.0.like": 1} }
);

我尝试使用以下方法创建它:

query = BCON_NEW ("_id", BCON_OID(&oid));
BSON_APPEND_UTF8 (query, "folders.folder_id", folderPositionRaw);
BSON_APPEND_UTF8 (query, "folders.files", "{" , "$elemMatch","{","file","5BD252AD-10C9-4DCE-A59C-5E3223BDDC60","}","}");

update = BCON_NEW ("$inc", 
    "{", 
    "folders.0.files.$.favorites.0.like", 1,
    "}");
mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);

但是方式是错误的。

编译时得到:

/current/set_fav.c: In function ‘main’:
/current/set_fav.c:102: warning: initialization discards qualifiers from pointer target type
/current/set_fav.c:168:122: error: macro "BSON_APPEND_UTF8" passed 9 arguments, but takes just 3
/current/set_fav.c:168: error: ‘BSON_APPEND_UTF8’ undeclared (first use in this function)
/current/set_fav.c:168: error: (Each undeclared identifier is reported only once /current/set_fav.c:168: error: for each function it appears in.)

仅供参考:folderPositionRaw 的值 3_root 在代码中设置得更高。


补充一点信息:原来我的Mongo语法错误,但C很高兴。我正在使用以下内容:

query = bson_new ();
bson_oid_init_from_string (&oid, tribe_id);
query = BCON_NEW ("_id", BCON_OID(&oid));       
BSON_APPEND_UTF8 (query, "folders.folder_id", folderPositionRaw);
BSON_APPEND_UTF8 (query, "folders.folder_id.$.files.file", file);

我的数据库团队给我提供了正确的 Mongo 语法(post 的顶部)的帮助,但在我尝试将其构建到 C BSON 中时我做错了。


一些进步:

我更新了我的代码,它们不再崩溃,这是一个好兆头,但是发送到 Mongo 的输出 JSON 的结构不完全正确。我认为问题是 mongo $inc 命令中发送的值 1 作为标量 1 而不是 int 1 发送。我已经尝试在 1 周围使用和不使用引号。使用引号运行代码,但不执行更新(不返回错误)。如果我删除引号,应用程序会崩溃。

query = bson_new ();
bson_oid_init_from_string (&oid, tribe_id);

query = BCON_NEW ("_id", BCON_OID(&oid), "folders.folder_id", folderPositionRaw,"folders.files", 
    "{",
        "$elemMatch",
            "{",
                "file", file,
            "}",
    "}");       

// Find the document
cursor = mongoc_collection_find (collection, MONGOC_QUERY_NONE, 0, 0, 0, query, NULL, NULL);

// update document
update = BCON_NEW ("$inc", 
    "{", 
        "folders.0.files.$.favorites.0.like","1",
    "}");

    str = bson_as_json (update, NULL);
    printf ("***-> %s <-***\n\n",str);

mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);

找到问题了!

您不能使用标准 int 它必须是 BCON_INT

update = BCON_NEW ("$inc", 
    "{", 
        "folders.0.files.$.favorites.0.like",BCON_INT32 (1),
    "}");

:)