问题
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().
Is this a right way? Everytime I finished a db action,
Connseems died. Or should I keep theConnrather than disconnect it to reuse it for next time? There's no global variable to keepConnso the only way I can think out to make it is to use something likegen_serverand keepConnin its State for reuse. Is this the right way?I also see there's a
connect_factorymethod. But I can't quite figure out the proper way to deal with it. Isconnect_factorya better way than connect to deal with large amount of db actions? And how to get a workableConnby usingconnect_factory?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:
- 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.
- 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.
- You can atomically increment using MongoDB. See http://www.mongodb.org/display/DOCS/Atomic+Operations, in particular findAndModify.
来源:https://stackoverflow.com/questions/6847866/whats-the-right-way-to-use-erlang-mongodb-driver-to-make-a-db-action