1

I have been messing around with this for a while now and have found no examples nor explanations about how to accomplish this task.

I have a collection of documents, each document has a date/time field. Ideally I need to generate a new field for each document where the value is based on the time from the date/time field with a constant factor added.

Alternatively, simply updating the value in place would suffice.

I have not been able to figure out how to reference the current document in a mongo shell update statement.

Is this folly? Should I give up and write an application do to complete this seemingly simple operation?

Thanks!

Steve Wagner
  • 254
  • 1
  • 3
  • 12

2 Answers2

2

Sometimes simply writing the question out brings you to a solution. Kinda hacky, and definitely weird, but seems to work:

db.actuals.find().forEach(
    function(d) { 
        var dt = d.date; 
        var ndt = new Date(d.date).setHours(dt.getHours() - 8); 
        db.actuals.update( {_id: d._id}, { $set: { local: new Date(ndt) } } );
    }
)
Steve Wagner
  • 254
  • 1
  • 3
  • 12
0

Its not folly and to anyone who's done any SQL programming its one of those things that you just assume is there and you are stunned to learn that it isn't. I too went looking for this at one point and came up empty. What you can do in the shell is script the conversion up by hand. Use the db.collection.find() to get the candidates and forEach your way over them. This is how we backup collections before we do big-ass migrations

db.config.find().forEach( function( x ) { db.config_20131119_bak.insert( x ) } );

What you don in the function may vary, but its worked pretty well for me.

Bob Kuhar
  • 10,838
  • 11
  • 62
  • 115