2013-10-06 22 views
1

我在數據庫中有一個文檔,如下所示。重命名嵌入式數組中的字段mongodb

{                
"CorePrice" : 1,          
"_id" : 166,           
"partno" : 76,           
"parttype" : "qpnm",         
"shipping" : [{                  
    "shippingMethod1" : "ground",       
    "cost1" : "10" 
     },              
    {      
      "shippingMethod2" : "air",        
     "cost2" : "11"         
    },              
    {                
    "shippingMethod3" : "USPS",        
    "cost3" : "3"         
    },              
    {                
    "shippingMethod4" : "USPS",        
    "cost4" : 45         
    }] 
} 

我想通過迭代使用下面的代碼重命名ShippingMethod4 shippingMethod。

remap = function (x)  
{ 
    if (x.shipping) { 
     db.foo.update ({ _id:x._id}, 
       { $set: {  
        "shipping.shippingMethod","x.shipping.shippingMethod4" },  
       $unset:{ "shipping.shippingMethod4":1  
     }}); } } 

但是它拋出我下面的錯誤:

"Sun Oct 06 02:09:44.764 JavaScript execution failed: SyntaxError: Unexpected token ,                    

不知道爲什麼。有人可以幫忙嗎?

+0

您不能引用一個字段並「拉」內容並存儲在另一個字段中。我建議,因爲這是一次性修復,只需抓住整個文檔,進行修復並更新文檔。 – WiredPrairie

+0

在$ set之後的「shipping.shippingMethod」之後有一個「,」。它應該是一個「:」;-)。但是這不會解決你的問題,因爲你仍然有錯誤。 – Moreno

回答

0

我已經爲你重寫了這個函數。

rename=function(x) { 
    if (x.shipping) { 
        x.shipping[3]={                
        "shippingMethod" : "USPS",        
        "cost4" : 45         
        } 
    } 
    db.foo.update({_id:x._id},x) 
} 

這將使您需要的更新。當然,對於一般情況,您仍然需要添加一個循環來遍歷shipping數組以找到所需的名稱,並讓索引像我一樣使用它,但是我將它作爲練習;-)。 您可以使用shell中的rename(x)來調用它。

希望這會有所幫助, 莫雷諾。

相關問題