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.
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 ;-). You call it with rename(x) from the shell.
Hope this helps, Moreno.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.