如何使用Go驱动程序或Golang在Mongodb中插入JavaScript函数

huangapple go评论134阅读模式
英文:

How to insert javascritpt function in Mongodb using Go driver or Golang

问题

我在MongoDB官方网站上看到了下面的代码,用于在MongoDB中插入一个JavaScript函数。

  1. db.system.js.save(
  2. {
  3. _id: "echoFunction",
  4. value : function(x) { return x; }
  5. }
  6. )

链接是:https://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/

我在mongoShell中尝试了这些步骤,效果很好。
现在,我想使用Golang将JavaScript函数存储到MongoDB中。

我在gopkg.in/mgo.v2/bson包中看到了下面的结构。

  1. // JavaScript是一个保存JavaScript代码的类型。如果Scope非空,它将被序列化为从标识符到值的映射,这些值在评估提供的代码时可以使用。
  2. type JavaScript struct {
  3. Code string
  4. Scope interface{}
  5. }

这是否与我期望的相关?
请分享你的知识。

英文:

I saw the below code in mongodb official site, to insert a Javascript function in mongodb.

  1. db.system.js.save(
  2. {
  3. _id: "echoFunction",
  4. value : function(x) { return x; }
  5. }
  6. )

link is:
https://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/

I tried the procedures in mongoShell and it is working good.
Now, I want to store javascript function in to mongodb using golang.

I saw the below structure in gopkg.in/mgo.v2/bson package.

  1. // JavaScript is a type that holds JavaScript code. If Scope is non-nil, it
  2. // will be marshaled as a mapping from identifiers to values that may be
  3. // used when evaluating the provided Code.
  4. type JavaScript struct {
  5. Code string
  6. Scope interface{}
  7. }

Does it relates to what I expected?
Please share your Knowledge.

答案1

得分: 1

以下是翻译好的内容:

这是如何创建一个返回bson.JavaScript结构的函数:

  1. func mongoNow() bson.JavaScript {
  2. return bson.JavaScript{
  3. // 在这里放入你的函数字符串
  4. Code: "(new Date()).ISODate('YYYY-MM-DD hh:mm:ss')"
  5. }
  6. }

然后插入到你的集合中:

  1. c := mongoSession.DB("YourDB").C("YourCollection")
  2. err := c.Insert(
  3. struct{ LastSeen interface{} }{
  4. LastSeen: mongoNow()
  5. }
  6. )

请不要忘记插入适当的import包。

英文:

Here is how First create a function that will return bson.JavaScript struct :

  1. func mongoNow() bson.JavaScript {
  2. return bson.JavaScript{
  3. // place your function in here in string
  4. Code: "(new Date()).ISODate('YYYY-MM-DD hh:mm:ss')"
  5. }
  6. }

And insert to your collections :

  1. c := mongoSession.DB("YourDB").C("YourCollection")
  2. err := c.Insert(
  3. struct{LastSeen interface{}}
  4. {
  5. LastSeen: mongoNow()
  6. }
  7. )

Please do not forget to insert your appropriate import package.

huangapple
  • 本文由 发表于 2017年5月8日 14:39:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/43841262.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定