2015-11-07 68 views
3

我想使用mongo c驅動程序更新單個文檔中的嵌套數組。下面是一個例子測試文檔:mongo c驅動程序更新嵌套數組

{ 
    "_id" : ObjectId("562416504bacd3940b8b2d5c"), 
    "folder1" : [ 
    { 
     "folder_id" : "5624200d4bacd3940b8b2d62", 
     "some" : "data" 
    }, 
    { 
     "folder_id" : "562940084bacf60575d3b17e", 
     "some" : "data" 
    } 
    ], 
    "folder2" : [ 
    { 
     "folder_id" : "5627e20d4bacefccf4864e4e", 
     "some" : "data" 
    } 
    ] 
} 

我想通過這兩個"folder1""folder2"迭代尋找匹配特定字符串(如:5624200d4bacd3940b8b2d62)任何"folder_id"。然後我希望從數組中刪除整個元素。所以刪除後我的文檔應該看起來像:

{ 
    "_id" : ObjectId("562416504bacd3940b8b2d5c"), 
    "folder1" : [ 
    { 
     "folder_id" : "562940084bacf60575d3b17e", 
     "some" : "data" 
    } 
    ], 
    "folder2" : [ 
    { 
     "folder_id" : "5627e20d4bacefccf4864e4e", 
     "some" : "data" 
    } 
    ] 
} 

我知道如何修改文檔中的單個元素,例如下面。但我還沒有找到任何通過嵌套數組元素迭代的好例子。

update = BCON_NEW ("$set", "{","some_cool_key", BCON_UTF8 ("some cool data for key"),"}"); 
mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error); 

回答

0

我想給John Moore @ ObjectRocket以幫助我。他提供了一個簡單的一行BCON,它完全符合我的需求:

update = BCON_NEW ("$pull", "{", "folder1", "{", "folder_id", BCON_UTF8 ("5624200d4bacd3940b8b2d62"), "}", "}"); 
+1

唯一的「缺點」是它只有folder1。爲了解決這個問題,我只需執行兩次命令(一次爲folder1,第二次爲folder2) –

相關問題