英文:
How can I ask MongoDB to evaluate some JavaScript in order to obtain value for a field?
问题
我想让MongoDB动态地为我插入的文档中的一个字段分配一个值。例如:从MongoDB服务器获取当前时间,就像MySQL中的NOW()函数一样。
我尝试了以下代码:
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, "无法在MongoDB服务器上注册。", 3)
我有这个辅助函数:
func mongoNow() bson.JavaScript {
return bson.JavaScript{Code:
"(new Date()).ISODate('YYYY-MM-DD hh:mm:ss')"}
}
LastSeen字段被存储为脚本而不是被评估:
[_id] => MongoId Object (
[$id] => 502d6f984eaead30a134fa10
)
[priority] => 1694546828
=> 127.0.0.1:8080
[lastseen] => MongoCode Object (
[code] => (new Date()).ISODate('YYYY-MM-DD hh:mm:ss')
[scope] => Array (
)
)
如何让一些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
=> 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
得分: 6
请参阅MongoDB文档中的以下URL:
> 有一个特殊的系统集合叫做system.js
,可以存储JavaScript函数以便重用。
但需要注意的是,服务器端代码(相当于存储过程)的支持和性能仍然有些不足(详细信息请参考链接)。
编辑:
要使用mgo驱动程序从Go调用存储过程,可以使用mgo.Database
类型的Run()
方法(直接链接),并使用要在服务器端执行的JavaScript代码作为参数发出eval
命令。类似于:
db.Run(bson.M{"eval": "myStoredFunction();"})
<sub>代码未经测试</sub>
在MongoDB的insert
语句中无法评估代码。
英文:
See the following URL on the MongoDB documentation:
> 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();"})
<sub>code untested</sub>
It is not possible to have code evaluated in a MongoDB insert
statement.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论