简体   繁体   English

重命名嵌入式数组mongodb中的字段

[英]rename a field in embedded array mongodb

I have a document in database as follows. 我在数据库中有一个文档,如下所示。

{                                                              
"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                                 
    }]
} 

I am trying to rename ShippingMethod4 to shippingMethod by iterating using the following code. 我试图通过使用以下代码进行迭代,将ShippingMethod4重命名为shippingMethod。

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

However it throws me the following error: 但是,它引发了以下错误:

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

Not sure why. 不知道为什么。 Can someone please help? 有人可以帮忙吗?

I have rewritten the function for you. 我已经为您重写了该功能。

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

This will make the update you need. 这将使您需要更新。 Of course, for a general case you still have to add a loop to iterate through the shipping array to find the name you want and keep the index to use it as I did, but I let you that as an exercise ;-). 当然,对于一般情况,您仍然必须添加一个循环以遍历shipping数组以查找所需的名称,并像我一样保留索引以使用它,但是我还是作为练习;-)。 You call it with rename(x) from the shell. 您可以从外壳中使用rename(x)进行调用。

Hope this helps, Moreno. 希望能有所帮助,莫雷诺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM