Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 373 lines (292 sloc) 17.457 kB
e7bc02e edoc annotations in src comments
Tony Hannan authored
1 %@doc Top-level client interface to MongoDB
9a01905 mongo.erl is top-level interface
Tony Hannan authored
2 -module (mongo).
3
4 -export_type ([maybe/1]).
5
f59460d mongo:create_index
Tony Hannan authored
6 -export_type ([host/0, connection/0]).
c6a4913 shorten factory names
Tony Hannan authored
7 -export ([connect/1, disconnect/1, connect_factory/1]).
b802070 is_closed. mongo: replica sets & pools
Tony Hannan authored
8 -export_type ([replset/0, rs_connection/0]).
c6a4913 shorten factory names
Tony Hannan authored
9 -export ([rs_connect/1, rs_disconnect/1, rs_connect_factory/1]).
f59460d mongo:create_index
Tony Hannan authored
10
11 -export_type ([action/1, db/0, write_mode/0, read_mode/0, failure/0]).
fe00618 auth & add_user
Tony Hannan authored
12 -export ([do/5, this_db/0]).
f59460d mongo:create_index
Tony Hannan authored
13
14 -export_type ([collection/0, selector/0, projector/0, skip/0, batchsize/0, modifier/0]).
9a01905 mongo.erl is top-level interface
Tony Hannan authored
15 -export ([insert/2, insert_all/2]).
16 -export ([save/2, replace/3, repsert/3, modify/3]).
17 -export ([delete/2, delete_one/2]).
18 -export ([find_one/2, find_one/3, find_one/4]).
19 -export ([find/2, find/3, find/4, find/5]).
20 -export ([count/2, count/3]).
f59460d mongo:create_index
Tony Hannan authored
21
22 -export_type ([cursor/0]).
23 -export ([next/1, rest/1, close_cursor/1]).
24
25 -export_type ([command/0]).
9a01905 mongo.erl is top-level interface
Tony Hannan authored
26 -export ([command/1]).
27
fe00618 auth & add_user
Tony Hannan authored
28 -export_type ([username/0, password/0]).
29 -export ([auth/2]).
30
31 -export_type ([permission/0]).
32 -export ([add_user/3]).
33
5a5ff25 create_index with optional fields allowed
Tony Hannan authored
34 -export_type ([index_spec/0, key_order/0]).
35 -export ([create_index/2]).
f59460d mongo:create_index
Tony Hannan authored
36
66853bc copy_database
Tony Hannan authored
37 -export ([copy_database/3, copy_database/5]).
38
9a01905 mongo.erl is top-level interface
Tony Hannan authored
39 -include ("mongo_protocol.hrl").
40
41 -type reason() :: any().
42
b802070 is_closed. mongo: replica sets & pools
Tony Hannan authored
43 % Server %
44
3f71a62 Host can no longer be raw ip address {,,,}. Connection includes host
Tony Hannan authored
45 -type host() :: mongo_connect:host().
46 % Hostname or ip address with or without port. Port defaults to 27017 when missing.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
47 % Eg. "localhost" or {"localhost", 27017}
48 -type connection() :: mongo_connect:connection().
49
50 -spec connect (host()) -> {ok, connection()} | {error, reason()}. % IO
e7bc02e edoc annotations in src comments
Tony Hannan authored
51 %@doc Connect to given MongoDB server
3f71a62 Host can no longer be raw ip address {,,,}. Connection includes host
Tony Hannan authored
52 connect (Host) -> mongo_connect:connect (Host).
9a01905 mongo.erl is top-level interface
Tony Hannan authored
53
54 -spec disconnect (connection()) -> ok. % IO
e7bc02e edoc annotations in src comments
Tony Hannan authored
55 %@doc Close connection to server
9a01905 mongo.erl is top-level interface
Tony Hannan authored
56 disconnect (Conn) -> mongo_connect:close (Conn).
57
5cbf4de Update types and Readme that referred to old pool name
Tony Hannan authored
58 -spec connect_factory (host()) -> resource_pool:factory(connection()).
59 %@doc Factory for use with a connection pool. See resource_pool module.
c6a4913 shorten factory names
Tony Hannan authored
60 connect_factory (Host) -> {Host, fun connect/1, fun disconnect/1, fun mongo_connect:is_closed/1}.
b802070 is_closed. mongo: replica sets & pools
Tony Hannan authored
61
62 % Replica Set %
63
64 -type replset() :: mongo_replset:replset().
65 -type rs_connection() :: mongo_replset:rs_connection().
66
67 -spec rs_connect (replset()) -> rs_connection(). % IO
e7bc02e edoc annotations in src comments
Tony Hannan authored
68 %@doc Create new cache of connections to replica set members starting with seed members. No connection attempted until rs_primary or rs_secondary_ok called.
b802070 is_closed. mongo: replica sets & pools
Tony Hannan authored
69 rs_connect (Replset) -> mongo_replset:connect (Replset).
70
71 -spec rs_disconnect (rs_connection()) -> ok. % IO
e7bc02e edoc annotations in src comments
Tony Hannan authored
72 %@doc Close cache of replset connections
b802070 is_closed. mongo: replica sets & pools
Tony Hannan authored
73 rs_disconnect (ReplsetConn) -> mongo_replset:close (ReplsetConn).
74
5cbf4de Update types and Readme that referred to old pool name
Tony Hannan authored
75 -spec rs_connect_factory (replset()) -> resource_pool:factory(rs_connection()).
76 %@doc Factory for use with a rs_connection pool. See resource_pool module.
c6a4913 shorten factory names
Tony Hannan authored
77 rs_connect_factory (Replset) -> {Replset, fun (RS) -> RC = rs_connect (RS), {ok, RC} end, fun rs_disconnect/1, fun mongo_replset:is_closed/1}.
b802070 is_closed. mongo: replica sets & pools
Tony Hannan authored
78
79 % Action %
80
9a01905 mongo.erl is top-level interface
Tony Hannan authored
81 -type action(A) :: fun (() -> A).
d6fd289 Fix wire protocol bit flags order. Catch not_master read and write er…
Tony Hannan authored
82 % An Action does IO, reads process dict {mongo_action_context, #context{}}, and throws failure()
9a01905 mongo.erl is top-level interface
Tony Hannan authored
83
84 -type failure() ::
d6fd289 Fix wire protocol bit flags order. Catch not_master read and write er…
Tony Hannan authored
85 mongo_connect:failure() | % thrown by read and safe write
fe00618 auth & add_user
Tony Hannan authored
86 mongo_query:not_master() | % thrown by read and safe write
87 mongo_query:unauthorized() | % thrown by read and safe write
88 write_failure() | % thrown by safe write
d6fd289 Fix wire protocol bit flags order. Catch not_master read and write er…
Tony Hannan authored
89 mongo_cursor:expired(). % thrown by cursor next/rest
9a01905 mongo.erl is top-level interface
Tony Hannan authored
90
91 -record (context, {
92 write_mode :: write_mode(),
93 read_mode :: read_mode(),
94 dbconn :: mongo_connect:dbconnection() }).
95
187d967 mongo:do accepts connnection() or rs_connection()
Tony Hannan authored
96 -spec do (write_mode(), read_mode(), connection() | rs_connection(), db(), action(A)) -> {ok, A} | {failure, failure()}. % IO
e7bc02e edoc annotations in src comments
Tony Hannan authored
97 %@doc Execute mongo action under given write_mode, read_mode, connection, and db. Return action result or failure.
aa1741b fix accepting rs_connection in mongo:do
Tony Hannan authored
98 do (WriteMode, ReadMode, Connection, Database, Action) -> case connection_mode (ReadMode, Connection) of
99 {error, Reason} -> {failure, {connection_failure, Reason}};
100 {ok, Conn} ->
101 PrevContext = get (mongo_action_context),
102 put (mongo_action_context, #context {write_mode = WriteMode, read_mode = ReadMode, dbconn = {Database, Conn}}),
103 try Action() of
104 Result -> {ok, Result}
105 catch
106 throw: E = {connection_failure, _, _} -> {failure, E};
107 throw: E = not_master -> {failure, E};
fe00618 auth & add_user
Tony Hannan authored
108 throw: E = unauthorized -> {failure, E};
aa1741b fix accepting rs_connection in mongo:do
Tony Hannan authored
109 throw: E = {write_failure, _, _} -> {failure, E};
110 throw: E = {cursor_expired, _} -> {failure, E}
111 after
112 case PrevContext of undefined -> erase (mongo_action_context); _ -> put (mongo_action_context, PrevContext) end
113 end end.
114
115 -spec connection_mode (read_mode(), connection() | rs_connection()) -> {ok, connection()} | {error, reason()}. % IO
e7bc02e edoc annotations in src comments
Tony Hannan authored
116 %@doc For rs_connection return appropriate primary or secondary connection
aa1741b fix accepting rs_connection in mongo:do
Tony Hannan authored
117 connection_mode (_, Conn = {connection, _, _}) -> {ok, Conn};
187d967 mongo:do accepts connnection() or rs_connection()
Tony Hannan authored
118 connection_mode (master, RsConn = {rs_connection, _, _}) -> mongo_replset:primary (RsConn);
119 connection_mode (slave_ok, RsConn = {rs_connection, _, _}) -> mongo_replset:secondary_ok (RsConn).
120
fe00618 auth & add_user
Tony Hannan authored
121 -spec this_db () -> db(). % Action
122 %@doc Current db in context that we are querying
123 this_db () -> {Db, _} = (get (mongo_action_context)) #context.dbconn, Db.
124
9a01905 mongo.erl is top-level interface
Tony Hannan authored
125 % Write %
126
127 -type write_mode() :: unsafe | safe | {safe, mongo_query:getlasterror_request()}.
128 % Every write inside an action() will use this write mode.
129 % unsafe = asynchronous write (no reply) and hence may silently fail;
130 % safe = synchronous write, wait for reply and fail if connection or write failure;
ba810a9 Add comment on getLastError
Tony Hannan authored
131 % {safe, Params} = same as safe but with extra params for getlasterror, see its documentation at http://www.mongodb.org/display/DOCS/getLastError+Command.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
132
133 -type write_failure() :: {write_failure, error_code(), bson:utf8()}.
134 -type error_code() :: integer().
135
136 -spec write (mongo_query:write()) -> ok. % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
137 %@doc Do unsafe unacknowledged fast write or safe acknowledged slower write depending on our context. When safe, throw write_failure if acknowledgment (getlasterror) reports error.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
138 write (Write) ->
139 Context = get (mongo_action_context),
140 case Context #context.write_mode of
141 unsafe -> mongo_query:write (Context #context.dbconn, Write);
142 SafeMode ->
0a8cc8c Documents are now tuples instead of lists
Tony Hannan authored
143 Params = case SafeMode of safe -> {}; {safe, Param} -> Param end,
9a01905 mongo.erl is top-level interface
Tony Hannan authored
144 Ack = mongo_query:write (Context #context.dbconn, Write, Params),
145 case bson:lookup (err, Ack) of
146 {} -> ok; {null} -> ok;
d6fd289 Fix wire protocol bit flags order. Catch not_master read and write er…
Tony Hannan authored
147 {String} -> case bson:at (code, Ack) of
148 10058 -> throw (not_master);
149 Code -> throw ({write_failure, Code, String}) end end end.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
150
151 -spec insert (collection(), bson:document()) -> bson:value(). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
152 %@doc Insert document into collection. Return its '_id' value, which is auto-generated if missing.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
153 insert (Coll, Doc) -> [Value] = insert_all (Coll, [Doc]), Value.
154
155 -spec insert_all (collection(), [bson:document()]) -> [bson:value()]. % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
156 %@doc Insert documents into collection. Return their '_id' values, which are auto-generated if missing.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
157 insert_all (Coll, Docs) ->
158 Docs1 = lists:map (fun assign_id/1, Docs),
159 write (#insert {collection = Coll, documents = Docs1}),
160 lists:map (fun (Doc) -> bson:at ('_id', Doc) end, Docs1).
161
162 -spec assign_id (bson:document()) -> bson:document(). % IO
e7bc02e edoc annotations in src comments
Tony Hannan authored
163 %@doc If doc has no '_id' field then generate a fresh object id for it
9a01905 mongo.erl is top-level interface
Tony Hannan authored
164 assign_id (Doc) -> case bson:lookup ('_id', Doc) of
165 {_Value} -> Doc;
0a8cc8c Documents are now tuples instead of lists
Tony Hannan authored
166 {} -> bson:append ({'_id', mongodb_app:gen_objectid()}, Doc) end.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
167
168 -spec save (collection(), bson:document()) -> ok. % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
169 %@doc If document has no '_id' field then insert it, otherwise update it and insert only if missing.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
170 save (Coll, Doc) -> case bson:lookup ('_id', Doc) of
fe00618 auth & add_user
Tony Hannan authored
171 {} -> insert (Coll, Doc), ok;
0a8cc8c Documents are now tuples instead of lists
Tony Hannan authored
172 {Id} -> repsert (Coll, {'_id', Id}, Doc) end.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
173
174 -spec replace (collection(), selector(), bson:document()) -> ok. % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
175 %@doc Replace first document selected with given document.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
176 replace (Coll, Selector, Doc) -> update (false, false, Coll, Selector, Doc).
177
178 -spec repsert (collection(), selector(), bson:document()) -> ok. % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
179 %@doc Replace first document selected with given document, or insert it if selection is empty.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
180 repsert (Coll, Selector, Doc) -> update (true, false, Coll, Selector, Doc).
181
182 -spec modify (collection(), selector(), modifier()) -> ok. % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
183 %@doc Update all documents selected using modifier
9a01905 mongo.erl is top-level interface
Tony Hannan authored
184 modify (Coll, Selector, Mod) -> update (false, true, Coll, Selector, Mod).
185
186 -spec update (boolean(), boolean(), collection(), selector(), bson:document()) -> ok. % Action
187 update (Upsert, MultiUpdate, Coll, Sel, Doc) ->
188 write (#update {collection = Coll, upsert = Upsert, multiupdate = MultiUpdate, selector = Sel, updater = Doc}).
189
190 -spec delete (collection(), selector()) -> ok. % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
191 %@doc Delete selected documents
9a01905 mongo.erl is top-level interface
Tony Hannan authored
192 delete (Coll, Selector) ->
193 write (#delete {collection = Coll, singleremove = false, selector = Selector}).
194
195 -spec delete_one (collection(), selector()) -> ok. % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
196 %@doc Delete first selected document.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
197 delete_one (Coll, Selector) ->
198 write (#delete {collection = Coll, singleremove = true, selector = Selector}).
199
200 % Read %
201
202 -type read_mode() :: master | slave_ok.
203 % Every query inside an action() will use this mode.
204 % master = Server must be master/primary so reads are consistent (read latest writes).
b802070 is_closed. mongo: replica sets & pools
Tony Hannan authored
205 % slave_ok = Server may be slave/secondary so reads may not be consistent (may read stale data). Slaves will eventually get the latest writes, so technically this is called eventually-consistent.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
206
207 slave_ok (#context {read_mode = slave_ok}) -> true;
208 slave_ok (#context {read_mode = master}) -> false.
209
210 -type maybe(A) :: {A} | {}.
211
212 -spec find_one (collection(), selector()) -> maybe (bson:document()). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
213 %@doc Return first selected document, if any
9a01905 mongo.erl is top-level interface
Tony Hannan authored
214 find_one (Coll, Selector) -> find_one (Coll, Selector, []).
215
216 -spec find_one (collection(), selector(), projector()) -> maybe (bson:document()). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
217 %@doc Return projection of first selected document, if any. Empty projection [] means full projection.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
218 find_one (Coll, Selector, Projector) -> find_one (Coll, Selector, Projector, 0).
219
220 -spec find_one (collection(), selector(), projector(), skip()) -> maybe (bson:document()). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
221 %@doc Return projection of Nth selected document, if any. Empty projection [] means full projection.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
222 find_one (Coll, Selector, Projector, Skip) ->
223 Context = get (mongo_action_context),
224 Query = #'query' {
225 collection = Coll, selector = Selector, projector = Projector,
226 skip = Skip, slaveok = slave_ok (Context) },
227 mongo_query:find_one (Context #context.dbconn, Query).
228
229 -spec find (collection(), selector()) -> cursor(). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
230 %@doc Return selected documents.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
231 find (Coll, Selector) -> find (Coll, Selector, []).
232
233 -spec find (collection(), selector(), projector()) -> cursor(). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
234 %@doc Return projection of selected documents. Empty projection [] means full projection.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
235 find (Coll, Selector, Projector) -> find (Coll, Selector, Projector, 0).
236
237 -spec find (collection(), selector(), projector(), skip()) -> cursor(). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
238 %@doc Return projection of selected documents starting from Nth document. Empty projection means full projection.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
239 find (Coll, Selector, Projector, Skip) -> find (Coll, Selector, Projector, Skip, 0).
240
241 -spec find (collection(), selector(), projector(), skip(), batchsize()) -> cursor(). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
242 %@doc Return projection of selected documents starting from Nth document in batches of batchsize. 0 batchsize means default batch size. Negative batch size means one batch only. Empty projection means full projection.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
243 find (Coll, Selector, Projector, Skip, BatchSize) ->
244 Context = get (mongo_action_context),
245 Query = #'query' {
246 collection = Coll, selector = Selector, projector = Projector,
247 skip = Skip, batchsize = BatchSize, slaveok = slave_ok (Context) },
248 mongo_query:find (Context #context.dbconn, Query).
249
250 -type cursor() :: mongo_cursor:cursor().
251
252 -spec next (cursor()) -> maybe (bson:document()). % IO throws mongo_connect:failure() & mongo_cursor:expired() (this is a subtype of Action)
e7bc02e edoc annotations in src comments
Tony Hannan authored
253 %@doc Return next document in query result cursor, if any.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
254 next (Cursor) -> mongo_cursor:next (Cursor).
255
256 -spec rest (cursor()) -> [bson:document()]. % IO throws mongo_connect:failure() & mongo_cursor:expired() (this is a subtype of Action)
e7bc02e edoc annotations in src comments
Tony Hannan authored
257 %@doc Return remaining documents in query result cursor.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
258 rest (Cursor) -> mongo_cursor:rest (Cursor).
259
260 -spec close_cursor (cursor()) -> ok. % IO (IO is a subtype of Action)
e7bc02e edoc annotations in src comments
Tony Hannan authored
261 %@doc Close cursor
9a01905 mongo.erl is top-level interface
Tony Hannan authored
262 close_cursor (Cursor) -> mongo_cursor:close (Cursor).
263
264 -spec count (collection(), selector()) -> integer(). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
265 %@doc Count selected documents
9a01905 mongo.erl is top-level interface
Tony Hannan authored
266 count (Coll, Selector) -> count (Coll, Selector, 0).
267
268 -spec count (collection(), selector(), integer()) -> integer(). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
269 %@doc Count selected documents up to given max number; 0 means no max. Ie. stops counting when max is reached to save processing time.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
270 count (Coll, Selector, Limit) ->
0a8cc8c Documents are now tuples instead of lists
Tony Hannan authored
271 CollStr = atom_to_binary (Coll, utf8),
272 Command = if
273 Limit =< 0 -> {count, CollStr, 'query', Selector};
274 true -> {count, CollStr, 'query', Selector, limit, Limit} end,
275 Doc = command (Command),
9a01905 mongo.erl is top-level interface
Tony Hannan authored
276 trunc (bson:at (n, Doc)). % Server returns count as float
277
278 % Command %
279
280 -type command() :: mongo_query:command().
281
282 -spec command (command()) -> bson:document(). % Action
e7bc02e edoc annotations in src comments
Tony Hannan authored
283 %@doc Execute given MongoDB command and return its result.
9a01905 mongo.erl is top-level interface
Tony Hannan authored
284 command (Command) ->
285 Context = get (mongo_action_context),
286 mongo_query:command (Context #context.dbconn, Command, slave_ok (Context)).
f59460d mongo:create_index
Tony Hannan authored
287
fe00618 auth & add_user
Tony Hannan authored
288 % Authentication %
289
290 -type username() :: bson:utf8().
291 -type password() :: bson:utf8().
292 -type nonce() :: bson:utf8().
293
294 -spec auth (username(), password()) -> boolean(). % Action
295 %@doc Authenticate with the database (if server is running in secure mode). Return whether authentication was successful or not. Reauthentication is required for every new pipe.
296 auth (Username, Password) ->
66853bc copy_database
Tony Hannan authored
297 Nonce = bson:at (nonce, command ({getnonce, 1})),
298 try command ({authenticate, 1, user, Username, nonce, Nonce, key, pw_key (Nonce, Username, Password)})
fe00618 auth & add_user
Tony Hannan authored
299 of _ -> true
300 catch error:{bad_command, _} -> false end.
301
302 -spec pw_key (nonce(), username(), password()) -> bson:utf8().
303 pw_key (Nonce, Username, Password) -> bson:utf8 (binary_to_hexstr (crypto:md5 ([Nonce, Username, pw_hash (Username, Password)]))).
304
305 -spec pw_hash (username(), password()) -> bson:utf8().
306 pw_hash (Username, Password) -> bson:utf8 (binary_to_hexstr (crypto:md5 ([Username, <<":mongo:">>, Password]))).
307
308 -spec binary_to_hexstr (binary()) -> string().
309 binary_to_hexstr (Bin) ->
310 lists:flatten ([io_lib:format ("~2.16.0b", [X]) || X <- binary_to_list (Bin)]).
311
312 -type permission() :: read_write | read_only.
313
314 -spec add_user (permission(), username(), password()) -> ok. % Action
315 %@doc Add user with given access rights (permission)
316 add_user (Permission, Username, Password) ->
317 User = case find_one (system.users, {user, Username}) of {} -> {user, Username}; {Doc} -> Doc end,
318 Rec = {readOnly, case Permission of read_only -> true; read_write -> false end, pwd, pw_hash (Username, Password)},
319 save (system.users, bson:merge (Rec, User)).
320
321 % Index %
f59460d mongo:create_index
Tony Hannan authored
322
5a5ff25 create_index with optional fields allowed
Tony Hannan authored
323 -type index_spec() :: bson:document().
324 % The following fields are required:
325 % key : key_order()
326 % The following fields are optional:
327 % name : bson:utf8()
328 % unique : boolean()
329 % dropDups : boolean()
330 % Additional fields are allowed specific to the index, for example, when creating a Geo index you may also supply
331 % min & max fields. See http://www.mongodb.org/display/DOCS/Geospatial+Indexing for details.
f59460d mongo:create_index
Tony Hannan authored
332
5a5ff25 create_index with optional fields allowed
Tony Hannan authored
333 -type key_order() :: bson:document().
334 % Fields to index on and whether ascending (1) or descending (-1) or Geo (<<"2d">>). Eg. {x,1, y,-1} or {loc, <<"2d">>}
f59460d mongo:create_index
Tony Hannan authored
335
5a5ff25 create_index with optional fields allowed
Tony Hannan authored
336 -spec create_index (collection(), index_spec() | key_order()) -> ok. % Action
337 %@doc Create index on collection according to given spec. Allow user to just supply key
338 create_index (Coll, IndexSpec) ->
339 Db = this_db (),
340 Index = bson:append ({ns, mongo_protocol:dbcoll (Db, Coll)}, fillout_indexspec (IndexSpec)),
341 insert ('system.indexes', Index).
f59460d mongo:create_index
Tony Hannan authored
342
5a5ff25 create_index with optional fields allowed
Tony Hannan authored
343 -spec fillout_indexspec (index_spec() | key_order()) -> index_spec().
344 % Fill in missing optonal fields with defaults. Allow user to just supply KeyOrder
345 fillout_indexspec (IndexSpec) -> case bson:lookup (key, IndexSpec) of
346 {} -> {key, IndexSpec, name, gen_index_name (IndexSpec), unique, false, dropDups, false};
347 {Key} -> bson:merge (IndexSpec, {key, Key, name, gen_index_name (Key), unique, false, dropDups, false}) end.
f59460d mongo:create_index
Tony Hannan authored
348
349 -spec gen_index_name (key_order()) -> bson:utf8().
350 gen_index_name (KeyOrder) ->
351 AsName = fun (Label, Order, Name) -> <<
6cdf847 fix gen_index_name
Tony Hannan authored
352 Name /binary, $_,
353 (atom_to_binary (Label, utf8)) /binary, $_,
354 (if
355 is_integer (Order) -> bson:utf8 (integer_to_list (Order));
356 is_atom (Order) -> atom_to_binary (Order, utf8);
357 is_binary (Order) -> Order;
358 true -> <<>> end) /binary >> end,
359 bson:doc_foldl (AsName, <<"i">>, KeyOrder).
f59460d mongo:create_index
Tony Hannan authored
360
66853bc copy_database
Tony Hannan authored
361 % Admin
362
363 -spec copy_database (db(), host(), db()) -> bson:document(). % Action
364 % Copy database from given host to the server I am connected to. Must be connected to 'admin' database.
365 copy_database (FromDb, FromHost, ToDb) ->
366 command ({copydb, 1, fromhost, mongo_connect:show_host (FromHost), fromdb, atom_to_binary (FromDb, utf8), todb, atom_to_binary (ToDb, utf8)}).
367
368 -spec copy_database (db(), host(), db(), username(), password()) -> bson:document(). % Action
369 % Copy database from given host, authenticating with given username and password, to the server I am connected to. Must be connected to 'admin' database.
370 copy_database (FromDb, FromHost, ToDb, Username, Password) ->
371 Nonce = bson:at (nonce, command ({copydbgetnonce, 1, fromhost, mongo_connect:show_host (FromHost)})),
372 command ({copydb, 1, fromhost, mongo_connect:show_host (FromHost), fromdb, atom_to_binary (FromDb, utf8), todb, atom_to_binary (ToDb, utf8), username, Username, nonce, Nonce, key, pw_key (Nonce, Username, Password)}).
Something went wrong with that request. Please try again.