erlmongo icon indicating copy to clipboard operation
erlmongo copied to clipboard

Erlang driver for MongoDB with gridfs that works with maps and proplists

https://github.com/Tobaloidee/erlmongo/blob/master/logo/erlmongo-logotype-horizontal.png = Info

Erlmongo is a pretty complete Erlang driver for mongodb.

All save/update/insert are safe and return if write succeeded.

It supports maps and proplists as datatypes. Strings can be lists or binaries, but strings received from mongodb (as a result of find) will be binaries.

Connections are pools (def. size 10) to master:

  • master/slave - read and write from master
  • master/master - pick a master at random and use it for everything
  • replica pairs/sets - find out which is master and connect to it

Always use an atom for naming pools. Name will be used for a public named ets table. Runtime connection API: mongodb:singleServer/1,2 mongodb:replicaPairs/3 mongodb:replicaSets/2 mongodb:masterSlave/3 mongodb:connect/1 mongodb:sharded/2

= Replica sets % List of servers does not have to be the entire list of the replica set. % Erlmongo will read the primary server from them and connect to it (even if not in the list). mongodb:replicaSets(mypool,["127.0.0.1:30000","127.0.0.1:30001"]). mongodb:connect(mypool).

= Examples make erl application:start(erlmongo). % Set mongodb server info. singleServer(PoolName) is the same as singleServer(PoolName,10,"localhost:27017") % NOTICE: Erlang 21 disabled tuple calls. You must call with mongoapi and last parameter Mong, e.g. mongoapi:count("user", Mong). mongodb:singleServer(def). mongodb:connect(def). % Create an interface for test database (it has to be a binary) Mong = mongoapi:new(def,<<"test">>).

% Save a new document Mong:save("mycollection",#{name => "MyDocument", i => 10}). % Return the document in map form Mong:findOne("mycollection", #{i => 10}, map).

% With proplists Mong:save("mydoc", [{"name", "MyDocument"}, {"i", 10}]). % Return only _id and name field Mong:findOne("mydoc", [{"i", 10}], [{"name", 1}]).

% Set Index. First parameter is so that the driver knows what collection % we mean. If you have an already constructed record laying around use that. % No need to construct a new record just so the driver can read the name. % Second parameter the index we wish to create. 1 = ascending, -1 = descending. Mong:ensureIndex("mycollection", [{#mydoc.i, 1}, {#mydoc.name, -1}])

% Find examples:

% Or M:find("mycollection",[{'or',[{"a",1},{"i",11}]}],undefined,0,100).

% Parameters: Search criteria, field selector, docs to skip, docs to return Mong:find("mycollection",#{i => 4}, #{name => 1}, 0, 10).

% Find with options Mong:findOpt("mycollection", #{i => 4}, undefined, [explain], 0, 0).

% Embedded records Mong:save("mycollection",#{name => "zembedom", i => 10, address = #{city => "ny", street => "some", country => "us"}}). Mong:find("mycollection",#{address => #{city => "la"}}, undefined, 0, 0).

% Advanced queries (supported: gt, lt, gte, lte, ne, in, nin, all, size, exists): % Documents with even i Mong:find("mycollection",#{i => {mod, 2, 0}}, undefined, 0,0). % Documents with i larger than 2: Mong:find("mycollection", #{i => {gt, 2}}, undefined, 0,0). % Documents with i between 2 and 5: Mong:find("mycollection", #{i => {in, {gt, 2}, {lt, 5}}}, undefined, 0,0). % in example: Mong:find("mycollection", #{tags => {in, [2,3,4]}}, undefined, 0,0). % exists example: Mong:find("mycollection", #{tags => {exists, false}}, undefined, 0,0).

% findandmodify command Mong:runCmd([{"findandmodify", "collectionname"},{"query", [{"fn","onmeta.flv"},{"ch","somechan"}]},{"remove",1}]).

% GridFS % Always run this on collection before writing the first file Mong:gfsIndexes(). {ok, Bin} = file:read_file("SomeFile"). % To open file for writing, use gfsNew PID = Mong:gfsNew("myfile"). % You can set parameters: mime, meta (embedded document), aliases (array of names), chunk size (default 256k) % flushLimit (at which buffer size data gets flushed to mongodb, def. 1MB) % PID = Mong:gfsNew("myfile", [{chunkSize, 100}]). % You can also set collection name (default is fd) % PID = Mong:gfsNew("myfilecol", "myfile", []). Mong:gfsWrite(PID,Bin). Mong:gfsClose(PID). % Reading PID = Mong:gfsOpen(#gfs_file{filename = "myfile"}). Res = Mong:gfsRead(PID,100000). Mong:gfsClose(PID).

= Supported Data types and modifiers Look at bson:encode_element/1

= SSL support You can use application environment variables or use set_ssl to establish connections over ssl before you connect with mongodb:connect. mongodb:set_ssl(true). % for ssl options use mongodb:set_ssl(true, SslOpts).

= Switching to mochijson's style proplists Mochijson library has a different string/list encoding convention: string = binary array = list You can choose a preferred way to encode with mongoapi:set_encode_style/1. Selected style is set to a selected server and table and not for mongoapi module instance. An example: ... 12> Mong:set_encode_style(default). ok 13> Mong:save("foobar", [{<<"data">>, [[1.1, 2.2], [3.3, 4.4]]}]). ** exception error: bad argument in function unicode:characters_to_binary/1 called as unicode:characters_to_binary([[1.1,2.2],[3.3,4.4]]) in call from mongodb:encode_cstring/1 in call from mongodb:encode_element/1 in call from mongodb:'-encode/2-fun-0-'/3 in call from lists:foldl/3 in call from mongodb:encode/2 in call from mongoapi:save/3 14> Mong:set_encode_style(mochijson). ok 15> Mong:save("foobar", [{<<"data">>, [[1.1, 2.2], [3.3, 4.4]]}]). {oid,<<"000af08b902dee723e000006">>}

== Supported operation list Collections

  • remove
  • save
  • insert
  • update
  • batchInsert
  • ensureIndex
  • deleteIndex
  • deleteIndexes
  • count
  • dropCollection
  • createCollection
  • group

Search

  • find
  • findopt
  • cursor - getMore - closeCursor
  • findOne

DB

  • eval
  • stats
  • runCmd
  • repairDatabase
  • cloneDatabase
  • dropDatabase
  • addUser
  • setProfilingLevel
  • getProfilingLevel

GridFS

  • gdsIndexes
  • gfsNew
  • gfsWrite
  • gfsOpen
  • gfsRead
  • gfsDelete
  • gfsFlush
  • gfsClose

== Author Sergej Jurečko