Commits

Jacob Perkins committed 6c146cf

emongo_collection distinct set & list, count & distinct command cleanup

Comments (0)

Files changed (2)

 	Packet = emongo_packet:ensure_index(Pool#pool.database, Collection, Pool#pool.req_id, Keys),
 	emongo_server:send(Pid, Pool#pool.req_id, Packet).
 
-count(PoolId, Collection) ->
-	{Pid, Pool} = gen_server:call(?MODULE, {pid, PoolId}, infinity),
-	Query = #emo_query{q=[{<<"count">>, Collection}, {<<"ns">>, Pool#pool.database}], limit=1},
-	Packet = emongo_packet:do_query(Pool#pool.database, "$cmd", Pool#pool.req_id, Query),
-	case emongo_server:send_recv(Pid, Pool#pool.req_id, Packet, ?TIMEOUT) of
-		#response{documents=[[{<<"n">>,Count}|_]]} ->
-			round(Count);
-		_ ->
-			undefined
-	end.
+count(PoolId, Collection) -> count(PoolId, Collection, []).
 
-count(PoolId, Collection, []) ->
-	count(PoolId, Collection);
 count(PoolId, Collection, Selector) ->
 	{Pid, Pool} = gen_server:call(?MODULE, {pid, PoolId}, infinity),
 	Q = [{<<"count">>, Collection}, {<<"ns">>, Pool#pool.database},
 			undefined
 	end.
 
-distinct(PoolId, Collection, Key) ->
-	{Pid, Pool} = gen_server:call(?MODULE, {pid, PoolId}, infinity),
-	Q = [{<<"distinct">>, Collection}, {<<"key">>, Key}, {<<"ns">>, Pool#pool.database}],
-	Query = #emo_query{q=Q, limit=1},
-	Packet = emongo_packet:do_query(Pool#pool.database, "$cmd", Pool#pool.req_id, Query),
-	case emongo_server:send_recv(Pid, Pool#pool.req_id, Packet, ?TIMEOUT) of
-		#response{documents=[[{<<"values">>, {array, Vals}} | _]]} ->
-			Vals;
-		_ ->
-			undefined
-	end.
+distinct(PoolId, Collection, Key) -> distinct(PoolId, Collection, Key, []).
 
-distinct(PoolId, Collection, Key, []) ->
-	distinct(PoolId, Collection, Key);
 distinct(PoolId, Collection, Key, Selector) ->
 	{Pid, Pool} = gen_server:call(?MODULE, {pid, PoolId}, infinity),
 	Q = [{<<"distinct">>, Collection}, {<<"key">>, Key}, {<<"ns">>, Pool#pool.database},

src/emongo_collection.erl

 
 -include("emongo.hrl").
 
+-export([distinct_set/4, distinct_list/4]).
 -export([fold/4, fold/5, fold/6]).
 -export([foreach/3, foreach/4, foreach/5]).
 
+%%%%%%%%%%%%%%
+%% distinct %%
+%%%%%%%%%%%%%%
+
+distinct_set(PoolId, Collection, Key, Selector) ->
+	F = fun({array, List}, Set) -> sets:union(Set, sets:from_list(List)) end,
+	Arrays = emongo:distinct(PoolId, Collection, Key, Selector),
+	lists:foldl(F, sets:new(), Arrays).
+
+distinct_list(PoolId, Collection, Key, Selector) ->
+	lists:sort(sets:to_list(distinct_set(PoolId, Collection, Key, Selector))).
+
 %%%%%%%%%%
 %% fold %%
 %%%%%%%%%%