Commits

Jacob Perkins committed 1d1b533

count command with selector

  • Participants
  • Parent commits 6143f9a

Comments (0)

Files changed (1)

File src/emongo.erl

 		 find_all/2, find_all/3, find_all/4, get_more/4,
 		 get_more/5, find_one/3, find_one/4, kill_cursors/2,
 		 insert/3, update/4, update/5, delete/2, delete/3,
-		 ensure_index/3, count/2, distinct/3, dec2hex/1, hex2dec/1]).
+		 ensure_index/3, count/2, count/3, distinct/3, dec2hex/1, hex2dec/1]).
 
 -include("emongo.hrl").
 
 			undefined
 	end.
 
+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},
+		 {<<"query">>, transform_selector(Selector)}],
+	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=[[{<<"n">>,Count}|_]]} ->
+			round(Count);
+		_ ->
+			undefined
+	end.
+
 distinct(PoolId, Collection, Key) ->
 	{Pid, Pool} = gen_server:call(?MODULE, {pid, PoolId}, infinity),
-	Query = #emo_query{q=[{<<"distinct">>, Collection}, {<<"key">>, Key}, {<<"ns">>, Pool#pool.database}], limit=1},
+	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}} | _]]} ->