[英]rename a field in embedded array 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 ,
不知道为什么。 有人可以帮忙吗?
我已经为您重写了该功能。
rename=function(x) {
if (x.shipping) {
x.shipping[3]={
"shippingMethod" : "USPS",
"cost4" : 45
}
}
db.foo.update({_id:x._id},x)
}
这将使您需要更新。 当然,对于一般情况,您仍然必须添加一个循环以遍历shipping数组以查找所需的名称,并像我一样保留索引以使用它,但是我还是作为练习;-)。 您可以从外壳中使用rename(x)进行调用。
希望能有所帮助,莫雷诺。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.