Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output to console in Mongo server-side javascript

Tags:

mongodb

Anybody figured out a way to output to a console inside a javascript function executing server-side in Mongo? Groovy code below:

DBCollection js = db.getCollection('system.js')
js.save([
    '_id' : 'product',
    value : new Code("""
        function(x,y) {
            alert('product called!');  // blows up...
            console.log('product called!');  // blows up...
            return x*y;
        }
    """
    )
])
js.eval('product(2,3)')
like image 282
Jonathan Schneider Avatar asked Dec 26 '22 12:12

Jonathan Schneider


1 Answers

There are two functions you can use to output from within JavaScript that is eval'd on the MongoDB server (including Map/Reduce functions):

  • print() - standard javascript print
  • printjson() - print as JSON

Both functions will emit their output into the mongod log, and can be useful for debugging.

like image 88
Stennie Avatar answered Jan 15 '23 17:01

Stennie