Where i can find examples of mongodb-erlang usage ?
The only source of information i found is this file:
https://github.com/TonyGen/mongodb-erlang/blob/master/src/mongodb_tests.erl
But it not covers many of basic queries like following (picked from MongoDB site):
db.collection.find().sort({name : 1, age: -1}).limit(10);
db.users.find().skip(20).limit(10);
db.things.ensureIndex({j:1});
db.things.find({colors : {$ne : "red"}});
db.collection.find({ "field" : { $gte: value } } );
db.things.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
So how to write these queries in terms of erlang driver ?
For the officially supported driver the API is documented here:
http://api.mongodb.org/erlang/mongodb/
For the find operations check out the function index, specifically:
http://api.mongodb.org/erlang/mongodb/mongo.html#find-2
If that is not to your taste, you may want to also check out the community drivers:
emongo/erlmongo - their respective READMEs and docs have some examples too:
https://bitbucket.org/rumataestor/emongo
https://github.com/wpntv/erlmongo
I have this similar issues too, here is my resolution with the offical mongodb-erlang driver:
1.The test mongodb records:
>db.erltest.find()
{ "_id" : ObjectId("4fe80d692f6cc055a32da380"), "x" : 1, "y" : 2 }
{ "_id" : ObjectId("4fe80d702f6cc055a32da381"), "x" : 2, "y" : 3 }
{ "_id" : ObjectId("4fe80d762f6cc055a32da382"), "x" : 10, "y" : 3 }
{ "_id" : ObjectId("4fe80d7e2f6cc055a32da383"), "x" : 10, "y" : 4 }
2.How to implement "db.erltest.find({x:{$gt:2}})" via mongodb-erlang?
-module(mongo_test2).
-export([tmp_test/0]).
-include ("/opt/Erlang/lib/erlang/lib/mongodb-master/include/mongo_protocol.hrl").
tmp_test() ->
application:start(mongodb),
Host = {localhost, 27017},
{ok, Conn} = mongo:connect(Host),
io:format("Conn is : ~p~n", [Conn]),
DbConn = {test, Conn},
Cursor = mongo_query:find(DbConn, #'query'{collection=erltest, selector={x, {'$gt', 2}}}),
process(Cursor),
mongo:disconnect(Conn).
process({}) ->
ok;
process(Cursor) ->
io:format("----Cursor:~p~n", [Cursor]),
Record = mongo:next(Cursor),
io:format("Record:~p~n", [Record]),
case Record of
{} ->
no_more;
_ ->
process(Cursor)
end.
Summaries:
- Please ensure include the correct path with the *mongo_protocol.hrl* file.
Cursor = mongo_query:find(DbConn, #'query'{collection=erltest, selector={x, {'$gt', 2}}})
is the detailed implement.
- Maybe mongodb_test.erl can supply more details for you.
- I'm an erlang newbie, for finding the above usage take me some time, hope this is helpful for you :)