【问题标题】:rename a field in embedded array mongodb重命名嵌入式数组 mongodb 中的字段
【发布时间】:2013-10-06 06:11:42
【问题描述】:

我在数据库中有一个文档如下。

{                                                              
"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 ,                                                                             

不知道为什么。有人可以帮忙吗?

【问题讨论】:

  • 您不能引用一个字段并“拉”出内容并存储在另一个字段中。我建议,因为这是一次性修复,所以只需获取整个文档,进行修复,然后更新文档。
  • $set 后面的“shipping.shippingMethod”后面有一个“,”。它应该是一个“:”;-)。但是,这不会解决您的问题,因为您仍然有错误。

标签: arrays mongodb field rename


【解决方案1】:

我已经为你重写了函数。

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

这将使您获得所需的更新。当然,对于一般情况,您仍然必须添加一个循环来遍历运输数组以找到您想要的名称并保持索引以像我一样使用它,但我让您将其作为练习 ;-)。 你在 shell 中用 rename(x) 调用它。

希望这会有所帮助, 莫雷诺。

【讨论】:

    猜你喜欢
    • 2019-01-27
    • 2013-09-06
    • 1970-01-01
    • 2012-02-25
    • 2014-11-03
    • 1970-01-01
    • 2020-09-25
    • 2021-03-29
    • 2014-12-10
    相关资源
    最近更新 更多