2016-08-25 185 views
1

我的數據如下,現在favoriteapi將有關鍵/值記錄進出。Mongodb嵌套插入

我如何將數據插入到該嵌套元素

{ 

"firstname": "ram5656", 
"lastname": "rahul", 
"email": "[email protected]", 
"password": "encrypt", 
"favoriteapi" : [ 
    { 
     "api_id" : "function", 
     "api_name" : "enterprise" 
    }, 
    { 
     "api_id" : "data_subject_category", 
     "api_name" : "address" 
    }, 
    { 
     "api_id" : "data_subject", 
     "api_name" : "address" 
    } 
], 
"is_active": true, 
"create_ts": "2016-05-18T00:00:00.000Z", 
"create_by": "[email protected]", 
"update_ts": "2016-05-18T06:00:00.000Z", 
"update_by": "[email protected]", 
"lastlogin": "2016-05-01T00:00:00.000Z" 

}

我想這

var updatedocument =  
    { 
     "api_id" : "sanket", 
     "api_name" : "sanket" 
    } 

user.favoriteapi.insert(updatedocument, options); 

,但沒有運氣。

我應該使用upsert嗎?

回答

0

你必須做你的用戶文檔的update,並指定要$push一個新的子文件到favouriteapi陣列。

var updatedocument = { 
    "api_id" : "sanket", 
    "api_name" : "sanket" 
}; 

db.user.update(
    {"email": "[email protected]"}, 
    {$push: { 
     "favouriteapi" : updatedocument 
    } 
    } 
); 
+0

謝謝文斯:) –