What is the correct way to use erlang mongodb driver to perform db action?

I am trying to use the official mongodb erlang driver. I read the document and still do not understand something. Hope someone tells me how to use it correctly:

Every time I do an action, I just write something like this:

{ok, Conn} = mongo:connect ({localhost, 27017}).
mongo:do (safe, master, Conn, test, fun() ->
    mongo:save (foo, {'_id', 1, bbb,22, y,2}),
    mongo:save (foo, {'_id', 4, bbb,22, y,2}) end).
mongo:disconnect().
  • Is it correct? Every time I finish the db action, Connit seems dead. Or should I save Connand not disable it for reuse next time? There is no global variable to save Conn, so the only way I can come up with is to use something like gen_serverand keep it Connin its state for reuse. Is it correct?

  • I also see a method there connect_factory. But I can’t figure out how to handle this properly. Is a connect_factorybetter way than connecting to work with a lot of db actions? And how to get workable Connwith connect_factory?

  • This is not a mongodb related issue. I want to provide each user with a unique number when visiting. So I saved the counter in db, when the user visits, the counter is added 1 and returned to the user as a unique number. But I always worry that two users get the same number when reading db at the same time. How can I make a unique counter incremented by 1 using mongodb?

Many thanks!

+1
source share
1 answer
+5

All Articles