How can I ask MongoDB to evaluate some JavaScript in order to obtain value for a field?

前端 未结 1 606
耶瑟儿~
耶瑟儿~ 2020-12-11 12:05

I want to let MongoDB dynamically assign a value to one of the fields of the document I\'m inserting. For example: the current time from MongoDB server just like NOW() woul

相关标签:
1条回答
  • 2020-12-11 12:43

    See the following URL on the MongoDB documentation:

    http://www.mongodb.org/display/DOCS/Server-side+Code+Execution#Server-sideCodeExecution-Storingfunctionsserverside

    There is a special system collection called system.js that can store JavaScript functions to be reused.

    Note though, that the support and performance of server-sided code (equivalent to stored procedures) is still a little poor (details in link).

    Edit:

    To call a stored procedure from Go using the mgo driver use the mgo.Database type's Run() method (direct link) and issue an eval command with the Javascript code to be executed server-side as argument. Something like:

    db.Run(bson.M{"eval": "myStoredFunction();"})
    

    code untested

    It is not possible to have code evaluated in a MongoDB insert statement.

    0 讨论(0)
提交回复
热议问题