We are refactoring a mongo database, and I'd like to pull the value for one field, and place it into a hash in array in another field. Here is how the data looks in the document before:
basecampURL: "https://basecamp.com/123/",
trackingSystems: [
{
type: "github",
url: "https://github.com/org/repo/issues/"
}
]
And here is what I'm hoping to accomplish:
trackingSystems: [
{
type: "basecamp",
url: "https://basecamp.com/123/"
},
{
type: "github",
url: "https://github.com/org/repo/issues/"
}
]
I've tried a few variations of this code, and where I'm running into an issue is when referencing the found variable for basecampURL, all of the examples on MongoDB Update are using a string.
db.projects.update(
{ basecampURL: '.+' },
{ $push:
{ trackingSystems:
{
type: 'basecamp',
url: basecampURL // this isn't valid, also tried $.basecampURL
}
},
$unset:
{ basecampURL: '.+' }
},
{ multi: true}
)
It seems like I'm not finding how to reference the found item's properties, but I've been wondering if I need to do store the found variable prior to the update.
You can achieve this using a javascript function similar to this:
db.coll.find({basecampURL : {$exists : true}}).forEach(
function(doc) {
var bc = {};
bc.type = "basecamp";
bc.url = doc.basecampURL;
doc.trackingSystems.push(bc);
// deletes the previous value
delete doc.basecampURL;
db.coll.save(doc);
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With