1

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.

2
  • @Speedy, did you ever figure this out? Despite Markus's dismissive comment, this is useful. The MongoDB documentation recommends using a similar function to implement an auto-increment field, for example. Commented Mar 8, 2016 at 23:31
  • 1
    @NathanSmith, I don't think mgo supports these types of queries which is a shame. Ended up replacing MongoDB with Bolt. Its much better as an embedded transactional database. Used disk space is 42 times smaller. Commented Mar 20, 2016 at 11:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.