What's the right way to use erlang mongodb dri

2019-06-02 09:52发布

问题:

I am trying official mongodb erlang driver. I read the doc and there's still something I can't understand. Hope anyone can tell me what's the right way to use it:

Every time I make an action, I just write something as follows:

{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().
  1. Is this a right way? Everytime I finished a db action, Conn seems died. Or should I keep the Conn rather than disconnect it to reuse it for next time? There's no global variable to keep Conn so the only way I can think out to make it is to use something like gen_server and keep Conn in its State for reuse. Is this the right way?

  2. I also see there's a connect_factory method. But I can't quite figure out the proper way to deal with it. Is connect_factory a better way than connect to deal with large amount of db actions? And how to get a workable Conn by using connect_factory?

  3. This is a question not quite related with mongodb. I want to give every user a unique number when they visit. So I saved a counter in db, when a user visit, the counter is added by 1 and returned to the user as the unique number. But I always have concern about two users get the same number with reading db at the same time. How can I make a unique counter increased by 1 using mongodb?

Thanks very much!

回答1:

  1. Conn may die if your action had an error, otherwise it should be reusable. Note, mongo:do returns {failure, X} on error. Don't disconnect Conn if you want to reuse it. BTW, disconnect takes Conn as an argument. If you want to keep Conn in a global var then consult the Erlang documentation for ways to do this (eg. ets table, gen_server, etc). Also, check out the mvar module in this driver for a simple gen_server that holds a value.
  2. connect_factory is used for maintaining a reusable pool of connections. Read the tutorial at http://github.com/TonyGen/mongodb-erlang. At the bottom it shows how to use connect_factory with resource_pool.
  3. You can atomically increment using MongoDB. See http://www.mongodb.org/display/DOCS/Atomic+Operations, in particular findAndModify.