douba8048 2012-08-17 15:42
浏览 50
已采纳

我如何要求MongoDB评估一些JavaScript以获得字段的价值?

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() would do in MySQL.

I tried this:

c := mongoSession.DB("myapp").C("instances")
rand.Seed(time.Now().UnixNano())
err := c.Insert(
   struct{Serial, Priority, Url, LastSeen interface{}}{ 
      Url: getInformedHost() + ":" + getRunningPortString(), 
      Priority: rand.Int(), 
      LastSeen: mongoNow() }
)
checkError(err, "Could not register on MongoDB server.", 3)

I have this helper function:

func mongoNow() bson.JavaScript {
    return bson.JavaScript{Code: 
         "(new Date()).ISODate('YYYY-MM-DD hh:mm:ss')"}
}

the LastSeen field gets stored as a script instead of evaluated:

[_id] => MongoId Object (
    [$id] => 502d6f984eaead30a134fa10
)
[priority] => 1694546828
[url] => 127.0.0.1:8080
[lastseen] => MongoCode Object (
    [code] => (new Date()).ISODate('YYYY-MM-DD hh:mm:ss')
    [scope] => Array (
    )
)

How can I get some javascript evaluated instead of inserted?

  • 写回答

1条回答 默认 最新

  • douchi7073 2012-08-17 16:30
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划