从mgo golang执行mongodb函数

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

execute mongodb functions from mgo golang

问题

在使用结构体对象进行更新或插入操作时,是否可以使用mgo驱动程序执行mongodb函数?

err := db.C(collectionName).UpdateId(eventID, Event{
    Name: eventName,
    Club: getClubName(clubID), //如何调用mongodb的getClubName函数?
})

我有一个mongodb函数,当给定一个俱乐部ID时,返回俱乐部名称。在mongodb shell中,以下命令可以正常执行:

db.loadServerScripts();
db.Event.update({"_id" : "30fc..."}, {"name": "foo_bar" , "clubName": getClubName("4df32...")});

我可以执行额外的数据库查询来获取俱乐部名称,但如果可能的话,我更希望这个操作是原子的。

英文:

Is it possible to use mgo driver to execute mongodb functions during an update or insert while using a struct object?

err := db.C(collectionName).UpdateId(eventID, Event{
	Name: eventName,
	Club: getClubName(clubID), //how to call mongodb getClubName function?
})

I have a mongodb function that returns a club name when given a club id. The following executes OK in the mongodb shell.

db.loadServerScripts();
db.Event.update({"_id" : "30fc..."}, {"name": "foo_bar" , "clubName": getClubName("4df32...")});

I can execute an additional database lookup to get the club name, but would prefer this to be atomic if possible.

答案1

得分: 1

根据类似的问题,在插入操作期间无法评估JavaScript。我认为可以安全地假设更新、upsert等操作也是如此。

您可以通过使用mgo的db.Run()方法来实现这一点,需要进行两次调用:

db.Run(bson.M{"eval": fmt.Sprintf("getClubName(%s);", clubID)}, &resp)

然后在更新语句中使用结果。

不幸的是,使用这种技术无法实现原子性。如果原子性是必需的,我建议将所有业务逻辑保留在应用程序中,并使用本地或基于数据库的锁定机制。

英文:

Per this similar question, there is no way to evaluate JavaScript during an insert. I think it's a safe assumption that the same goes for updates, upserts, etc.

You can achieve this in two calls by using mgo's db.Run() method:

db.Run(bson.M{"eval": fmt.Sprintf("getClubName(%s);", clubID)}, &resp)

And then using the result in your update statement.

Unfortunately, there is no way to make things atomic using this technique. If atomicity is a requirement, I would recommend keeping all the business logic in your application and using a local or database-based locking mechanism.

huangapple
  • 本文由 发表于 2016年2月10日 05:46:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/35302810.html
匿名

发表评论

匿名网友

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

确定