Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving mongo field within document if it exists

Tags:

mongodb

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.

like image 634
brock Avatar asked Dec 12 '22 12:12

brock


1 Answers

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);
   }
)
like image 101
Ori Dar Avatar answered Jan 05 '23 20:01

Ori Dar