c - Mongo C驱动: Insert element into nested array

标签 c arrays mongodb mongo-c-driver

早上好,

我对 MongoDB 和使用 c 驱动程序都很陌生,所以这个问题对某些人来说可能看起来微不足道,但我完全不知所措。

我有一个文档,其中有一个名为“folders”的数组,文件夹的每个元素内都有一个名为“files”的辅助数组。我希望为特定文件夹的数组添加一个条目到"file"中。

我尝试在c中使用$push创建一个BCON,但我知道我已经完全搞砸了。我没有收到任何编译错误,并且可以运行该应用程序,但文档没有任何反应。我认为我的应用程序在执行此代码时中止,因为它后面有一个 printf 无法打印,但如果我从代码中删除“update =”和“mongoc_collection_update”行,则所有内容都会正确执行。所以我认为我的问题是实际的 bcon 结构是错误的并导致 exec 出现错误。

示例文档

{ 
"_id" : ObjectId("5627e20d4bacefccf4864e4e"), 
"allow_save" : "true", 
"allow_add" : "true", 
"auto_approve_invites" : "true", 
"folders" : [
    {
        "folder_id" : "root", 
        "display_name" : "My Folder", 
        "files" : [
            {
                "modified" : "", 
                "file" : "58656607-801b-40e4-aa34-e01ef1def85b"
            }, 
            {
                "modified" : "", 
                "file" : "58656607-801b-40e4-aa34-e01ef1def85b"
            }, 
            {
                "modified" : "", 
                "file" : "58656607-801b-40e4-aa34-e01ef1def85b"
            }
        ]
    }, 
    {
        "folder_id" : "1", 
        "display_name" : "My Other Folder", 
        "preview_thumbnail" : "58656607-801b-40e4-aa34-e01ef1def85b", 
        "files" : [
            {
                "modified" : "", 
                "file" : "58656607-801b-40e4-aa34-e01ef1def85b"
            }, 
            {
                "modified" : "", 
                "file" : "58656607-801b-40e4-aa34-e01ef1def85b"
            }, 
            {
                "modified" : "", 
                "file" : "58656607-801b-40e4-aa34-e01ef1def85b"
            }
        ]
    }
]
}

代码示例

collection = mongoc_client_get_collection (client, "***", "***");

update = bson_new ();
bson_oid_t oid;
bson_oid_init_from_string (&oid, tribe_id);
update = BCON_NEW ("_id", BCON_OID(&oid));

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

// add new file
update = BCON_NEW ("$push", 
        "{","folders.folder_id", BCON_UTF8 ("root"), "}",
        "{","new_file", "new value", "}");

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

最佳答案

update = BCON_NEW ("$push", "{", "folders.0.files", "{", "file", BCON_UTF8 ("XXXXXXXXX"), "modified", BCON_UTF8 (""), "}", "}");

找到解决方案。

关于c - Mongo C驱动: Insert element into nested array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33635256/

相关文章:

mongodb - 3-空间中的 k 最近邻查询

node.js - Nodejs MongoDb 异步回调

c - 如何将 char 数组转换为 float 并检查其范围?

c - 为什么这个 C 程序会遇到运行时错误?

小时字符串数组中的 Ruby 最小值和最大值

C 使用指针调用函数时出现问题

java - MongoDB Spring 数据聚合平均值

c - 将newNode按升序插入LinkedList

C 从字符串中提取数字

javascript - js从两个数组中删除对象引用