-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongo.m
1824 lines (1464 loc) · 63.5 KB
/
mongo.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
classdef mongo < handle & matlab.mixin.CustomDisplay
% MONGO connect to a mongo database
%
% CONNECT = MONGO(SERVER,PORT,DATABASE)
% returns Mongo database object
%
% CONNECT = MONGO(SERVER,PORT,DATABASENAME,'NAME','VALUE')
% returns Mongo database object with additional name-value arguments. For
% instance, you can specify UserName and Password required for
% authentication against the database.
%
% Input Arguments:
% ----------------
% SERVER - List of servers hosting Mongo database.
% PORT - List of port-numbers associated to each server.
% DATABASE - Mongo database name to connect to.
%
% Name-Value arguments:
% ---------------------
% UserName - username required to authorize user.
% Password - password required to authenticate a username.
%
% Methods:
% --------
%
% isopen - Check if connection to Mongo database is valid
% close - Close conection to Mongo database
% createCollection - Create a Mongo Collection
% dropCollection - Drop a Mongo Collection
% count - Count total documents in a collection or for a Mongo
% Query
% distinct - Get distinct values in a field of documents in a
% collection or for a Mongo Query
% find - Find and retrieve documents in a collection or for a
% Mongo Query
% aggregate - process data records and return computed results
% insert - Insert data in MATLAB as documents in a Mongo
% collection
% update - Update data in documents stored in a Mongo
% collection
% remove - Remove documents from a Mongo collection
%
% Example:
% --------
% conn = mongo("localhost",27017,"testdb")
%
% conn = mongo("localhost",27017,"testdb","UserName","testdbuser","Password","pass1")
%
% conn = mongo(["localhost" "remotehost"],[27017,27018],"testdb","UserName","testdbuser","Password","pass1")
%
% Copyright 2017 The MathWorks, Inc.
% Updated to v3.12.0 (2019 by horsche)
properties(SetAccess = private)
% Stores the name of the database provided
Database;
% Stores the username used to authenticate
UserName;
% Stores the name of the Server(s) to which connection is established
Server;
Port; % 0 or more MongoDB Server Port
% List of Collections present in the database
CollectionNames;
% Total number of Documents across all Collections in database
TotalDocuments;
% Processing time of last query
QueryDuration;
end
properties(Access = private, Hidden = true)
% Stores handle to 'DB' object of Mongo-JAVA driver
DatabaseHandle;
% Stores handle to 'Mongo' object of Mongo-JAVA driver
ConnectionHandle;
end
methods(Static, Hidden = true, Access = private)
function errmessage = extractExceptionMessage(e)
if strcmpi(e.identifier,'MATLAB:Java:GenericException')
exceptionObj = e.ExceptionObject;
errmessage = char(exceptionObj.getMessage);
else
errmessage = e.message;
end
end
end % methods(Static, Hidden = true, Access = private)
methods(Static, Hidden = false, Access = private)
% parse special json output types (ObjectId, Date, ...)
function document = parseJson2Output(document)
% special types are always single structs
if iscell(document) && length(document) == 1
document = document{1};
end
if ~isstruct(document)
return;
end
% check for fieldnames
fNames = fieldnames(document);
if length(fNames) > 1 || isstruct(document.(fNames{1})) || iscell(document.(fNames{1}))
% recursive on all structs
fNames = fNames(structfun(@isstruct, document) | structfun(@iscell, document));
for i = 1:length(fNames)
c = arrayfun(@mongo.parseJson2Output, document.(fNames{i}), 'UniformOutput', false);
if iscell(document.(fNames{i}))
document.(fNames{i}) = c;
else
document.(fNames{i}) = [c{:}];
end
end
else
% single structure with special type
switch lower(fNames{1})
case {'x_oid'}
% mongodb ObjectId
document = document.(fNames{1});
case {'x_date'}
% date object (milliseconds from 1-Jan-1970 UTC)
tz = 'UTC';
document = datetime(document.(fNames{1})/1000, 'ConvertFrom', 'posixtime', 'TimeZone', tz);
case {'x_numberlong'}
% mongodb long number
document = str2double( document.(fNames{1}) );
otherwise
% single struct but nothing to parse
end
end
end
% parse input with special types (ObjectId, Date, ...)
function str = parseInput2Json(document)
document = singleStructTypes(document);
str = jsonencode(document);
% replace "x_" by special char "$"
str = strrep(str, '"x_', '"$');
% replace ignore special char "X_"
str = strrep(str, '"X_', '"x_');
% set "_id" fieldname
str = strrep(str, '"$id"', '"_id"');
% set "_parent" fieldname
str = strrep(str, '"$parent"', '"_parent"');
function document = singleStructTypes(document)
if ~isstruct(document)
return;
end
% check for fieldnames
fNames = fieldnames(document);
for i = 1:length(fNames)
% mongodb ObjectId {"_id": {"$oid": "5e00d6ba1f359f46b0ac492b"}}
if contains(fNames{i}, {'x_id' 'x_oid'}) && (ischar(document.(fNames{i})) || isstring(document.(fNames{i})))
if sum(contains(fNames, {'x_id' 'x_oid'})) > 1
% warning(com.mongodb.MongoException(sprintf('Multiple ObjectIds found (%s)', strjoin(fNames(contains(fNames, {'x_id' 'x_oid'})), ', '))));
warning('Multiple ObjectIds found, ignore ''%s''', fNames{i});
document = renameStructField(document, fNames{i}, ['X_' fNames{i}(3:end)]);
continue;
end
x_id.x_oid = document.(fNames{i});
document = rmfield(document, fNames{i});
document.x_id = x_id;
continue;
end
% mongodb ObjectId {"_parent": {"$oid": "5e00d6ba1f359f46b0ac492b"}}
if contains(fNames{i}, {'x_parent'}) && (ischar(document.(fNames{i})) || isstring(document.(fNames{i})))
if sum(contains(fNames, {'x_id' 'x_oid'})) > 1
% warning(com.mongodb.MongoException(sprintf('Multiple ObjectIds found (%s)', strjoin(fNames(contains(fNames, {'x_id' 'x_oid'})), ', '))));
warning('Multiple ObjectIds found, ignore ''%s''', fNames{i});
document = renameStructField(document, fNames{i}, ['X_' fNames{i}(3:end)]);
continue;
end
x_id.x_oid = document.(fNames{i});
document = rmfield(document, fNames{i});
document.x_parent = x_id;
continue;
end
% mongodb date {"now": {"$date": 1577457427400}}
if isdatetime(document.(fNames{i}))
% datenum in milliseconds since 01-Jan-1970 (UTC)
x_date.x_date = (max([datenum(document.(fNames{i})), datenum('01-Jan-1970')]) - datenum('01-Jan-1970')) * 86400000;
document.(fNames{i}) = x_date;
continue;
end
% parse recursive
if isstruct(document.(fNames{i}))
document.(fNames{i}) = singleStructTypes(document.(fNames{i}));
end
end
end
end
end % methods(Static, Hidden = false, Access = private)
methods(Static, Hidden = false, Access = public)
% Date-related operations
function num = date2num(date)
%DATE2NUM converts date to mongodb number of milliseconds since the
% Unix epoch (Jan 1, 1970).
%
% NUM = DATE2NUM(DATE)
%
% Input arguments:
% ----------------
% DATE - Matlab datetime object
%
% Example:
% --------
% num = date2num(datetime)
%
% 2020 by horsche
p = inputParser;
p.addRequired("date",@(x)validateattributes(x,"datetime",{"scalar"}));
p.parse(date);
try
num = (datenum(date) - datenum('01-Jan-1970')) * 86400000;
catch e
throw(e);
end
end
function str = date2str(date)
%DATE2STR converts date to string representing mongodb number of
% milliseconds since the Unix epoch (Jan 1, 1970).
%
% STR = DATE2STR(DATE)
%
% Input arguments:
% ----------------
% DATE - Matlab datetime object
%
% Example:
% --------
% str = date2str(datetime)
%
% 2020 by horsche
p = inputParser;
p.addRequired("date",@(x)validateattributes(x,"datetime",{"scalar"}));
p.parse(date);
try
str = num2str((datenum(date) - datenum('01-Jan-1970')) * 86400000);
catch e
throw(e);
end
end
function date = num2date(num, timezone)
%DATE2NUM converts mongodb date number to matlab date object.
%
% DATE = NUM2DATE(NUM, TIMEZONE)
%
% Input arguments:
% ----------------
% NUM - mongodb number of milliseconds since the Unix
% epoch (Jan 1, 1970).
%
% TIMEZONE - selected timezone
%
% Example:
% --------
% date = num2date(1577923200000)
%
% 2020 by horsche
p = inputParser;
p.addRequired("date",@(x)validateattributes(x,"datetime",{"scalar"}));
p.addOptional("timezone",'UTC',@(x)validateattributes(x,{"string","char"},{"scalar"}));
p.parse(num, timezone);
date = datetime(num/1000, 'ConvertFrom', 'posixtime', 'TimeZone', timezone);
end
end % methods(Static, Hidden = false, Access = public)
methods(Access = public, Hidden = true)
% Returns connection handle
function connHandle = getConnHandle(mongodbconn)
connHandle = mongodbconn.ConnectionHandle;
end
% Returns database handle
function dbHandle = getDBHandle(mongodbconn)
dbHandle = mongodbconn.DatabaseHandle;
end
end % methods(Access = public, Hidden = true)
methods
function collectionnames = get.CollectionNames(mongodbconn)
collectionnames = {};
try
% Invoke Mongo-JAVA Driver API to obtain list of collections
colllist = mongodbconn.DatabaseHandle.getCollectionNames;
% Manually iterate through the list and build a CELL ARRAY
iter = colllist.iterator;
while (iter.hasNext)
collectionnames = [collectionnames; iter.next()];
end
collectionnames = collectionnames';
catch
collectionnames = {};
end
end
function totaldocuments = get.TotalDocuments(mongodbconn)
try
totaldocuments = mongodbconn.DatabaseHandle.getStats.get('objects');
catch
totaldocuments = [];
end
end
end % methods
methods(Access = public, Hidden = true)
function mongodbconn = mongo(server,port,database,varargin)
if nargin == 0
return;
end
if (exist('com.mongodb.MongoCredential','class') ~= 8 || ...
exist('com.mongodb.MongoClient','class') ~= 8 || ...
exist('com.mongodb.MongoClientOptions','class') ~= 8 || ...
exist('com.mongodb.WriteConcern','class') ~= 8 || ...
exist('com.mongodb.ReadPreference','class') ~= 8 || ...
exist('com.mongodb.ServerAddress','class') ~= 8)
error(message('mongodb:mongodb:driverNotFound'));
end
import org.apache.log4j.*;
Logger.getRootLogger().setLevel(Level.OFF);
% Input parser to input validation
p = inputParser;
p.addRequired("server",@(x)validateattributes(x,["string" "char" "cell"],{}))
p.addRequired("port",@(x)validateattributes(x,"numeric",{"row","nonnegative","nonnan","positive","finite"}));
p.addRequired("database",@(x)validateattributes(x,["string" "char"],{"scalartext"}));
p.addParameter("UserName","",@(x)validateattributes(x,["string" "char"],{"scalartext"}));
p.addParameter("Password","",@(x)validateattributes(x,["string" "char"],{"scalartext"}));
p.addParameter("AuthMechanism","",@(x)validateattributes(x,["string" "char"],{"scalartext"}));
p.addParameter("ConnectionTimeout",10000,@(x)validateattributes(x,"numeric",{"scalar","nonnan","nonnegative","positive","finite"}));
p.addParameter("ServerSelectionTimeout",10000,@(x)validateattributes(x,"numeric",{"scalar","nonnan","nonnegative","positive","finite"}));
p.addParameter("ReadPreference","",@(x)validateattributes(x,["string" "char"],{"scalartext"}));
p.addParameter("WriteConcern","",@(x)validateattributes(x,["string" "char"],{"scalartext"}));
p.addParameter("SSLEnabled", false, @(x)validateattributes(x,"logical",{"scalar"}));
p.parse(server,port,database,varargin{:});
server = p.Results.server;
if isempty(server)
error(message('mongodb:mongodb:IncorrectDataType','server'));
end
switch class(server)
case {'string','char'}
server = cellstr(server);
if any(cellfun(@isempty, server) == 1)
error(message('mongodb:mongodb:IncorrectDataType','server'));
end
case {'cell'}
if ~all(cellfun(@ischar, server) == 1) || any(cellfun(@isempty, server) == 1)
error(message('mongodb:mongodb:IncorrectDataType','server'));
end
server = cellstr(p.Results.server);
end
port = p.Results.port;
databasename = char(p.Results.database);
if isempty(databasename)
error(message('mongodb:mongodb:ExpectedNonempty','database'));
end
username = char(p.Results.UserName);
password = char(p.Results.Password);
authmechanism = char(p.Results.AuthMechanism);
connectiontimeout = p.Results.ConnectionTimeout;
serverselectiontimeout = p.Results.ServerSelectionTimeout;
readpreference = char(p.Results.ReadPreference);
writeconcern = char(p.Results.WriteConcern);
sslEnabled = logical(p.Results.SSLEnabled);
% Length of SERVER and PORT CELL array should match, else, PORT
% should be of length 1
if length(port) ~= length(server)
error(message('mongodb:mongodb:PortServerSizeMismatch'))
end
if ~isempty(password) && isempty(username)
password = "";
end
if ~isempty(readpreference)
readpreference = validatestring(readpreference,{'nearest','primary','secondary','primarypreferred','secondarypreferred'});
end
if ~isempty(writeconcern)
writeconcern = validatestring(writeconcern,{'acknowledged','majority','w1','w2','w3'});
end
if ~isempty(authmechanism)
authmechanism = validatestring(p.Results.AuthMechanism,{'MONGODB_CR','PLAIN','SCRAM_SHA_1'});
end
try
% Invoke UTILITY function to build an ArrayList of SERVER
% ADDRESSES - Mongo ServerAddress API
serverAddrList = java.util.ArrayList;
for i = length(server)
serverAddrList.add(com.mongodb.ServerAddress(server{i},port(i)));
end
% Set ConnectTimeout and ServerSelectionTimeout options to minimize network traffic
options = com.mongodb.MongoClientOptions.builder();
options = options.connectTimeout(connectiontimeout);
options = options.serverSelectionTimeout(serverselectiontimeout);
options = options.sslEnabled(sslEnabled);
if ~isempty(readpreference)
switch readpreference
case {'nearest'}
options = options.readPreference(com.mongodb.ReadPreference.nearest());
case {'primary'}
options = options.readPreference(com.mongodb.ReadPreference.primary());
case {'secondary'}
options = options.readPreference(com.mongodb.ReadPreference.secondary());
case {'primarypreferred'}
options = options.readPreference(com.mongodb.ReadPreference.primaryPreferred());
case {'secondarypreferred'}
options = options.readPreference(com.mongodb.ReadPreference.secondaryPreferred());
end
end
if ~isempty(writeconcern)
switch writeconcern
case {'acknowledged'}
options = options.writeConcern(com.mongodb.WriteConcern.ACKNOWLEDGED);
case {'majority'}
options = options.writeConcern(com.mongodb.WriteConcern.MAJORITY);
case {'w1'}
options = options.writeConcern(com.mongodb.WriteConcern.W1);
case {'w2'}
options = options.writeConcern(com.mongodb.WriteConcern.W2);
case {'w3'}
options = options.writeConcern(com.mongodb.WriteConcern.W3);
end
end
options = options.build();
% Create a MONGO DATABASE OBJECT for each DATABASENAME provide
if ~isempty(username) && ~isempty(password)
credentialList = java.util.ArrayList;
% Invoke appropriate JAVA driver method based on
% AUTHMECHANISM provided
switch authmechanism
case 'MONGODB_CR'
credential = com.mongodb.MongoCredential.createMongoCRCredential(username,databasename,password);
case 'PLAIN'
credential = com.mongodb.MongoCredential.createPlainCredential(username,databasename,password);
case 'SCRAM_SHA_1'
credential = com.mongodb.MongoCredential.createScramSha1Credential(username,databasename,password);
otherwise
credential = com.mongodb.MongoCredential.createCredential(username,databasename,password);
end
credentialList.add(credential);
mongodbconn.ConnectionHandle = com.mongodb.MongoClient(serverAddrList,credentialList,options);
mongodbconn.UserName = username;
else
mongodbconn.ConnectionHandle = com.mongodb.MongoClient(serverAddrList,options);
mongodbconn.UserName = '';
end
mongodbconn.Database = databasename;
% Check if authentication passed
mongodbconn.ConnectionHandle.getAddress;
% Try to get database instance
mongodbconn.DatabaseHandle = mongodbconn.ConnectionHandle.getDB(databasename);
% Construct Mongo object only if connection is successful
mongodbconn.Server = server;
mongodbconn.Port = port;
mongodbconn.CollectionNames = {};
try
% Invoke Mongo-JAVA Driver API to obtain list of collections
colllist = mongodbconn.DatabaseHandle.getCollectionNames;
% Manually iterate through the list and build a CELL ARRAY
iter = colllist.iterator;
while (iter.hasNext)
mongodbconn.CollectionNames = [mongodbconn.CollectionNames; iter.next()];
end
mongodbconn.CollectionNames = mongodbconn.CollectionNames';
catch
mongodbconn.CollectionNames = {};
end
mongodbconn.TotalDocuments = [];
try
mongodbconn.TotalDocuments = mongodbconn.DatabaseHandle.getStats.get('objects');
catch
mongodbconn.TotalDocuments = [];
end
catch e
% Clean - up activity
% First close the connection to the server to avoid
% orphaned objects
if ~isempty(mongodbconn.ConnectionHandle)
mongodbconn.ConnectionHandle.close;
end
error(message('mongodb:mongodb:DriverError',mongo.extractExceptionMessage(e)));
end
end
end % methods(Access = public, Hidden = true)
methods(Access = public)
% Database-related operations
function close(mongodbconn)
%CLOSE close mongo database connection
%
% Input arguments:
% ----------------
% MONGODBCONN - Mongo database object
%
% Example:
% --------
% close (mongodbconn)
%
% Copyright 2017 The MathWorks, Inc.
validateattributes(mongodbconn,"mongo",{"scalar"});
if ~isopen(mongodbconn)
if isvalid(mongodbconn)
mongodbconn.delete;
end
return;
end
% Get connection handle
connectionHandle = getConnHandle(mongodbconn);
% Close the connection
connectionHandle.close;
% Update the Object properties
mongodbconn.delete;
end
function val = isopen(mongodbconn)
%ISOPEN Check if database connection is valid
%
% returns true(1) if database connection is open ,else returns
% false(0)
%
% Input arguments:
% ----------------
% mongodbconn - Mongo database object
%
% Example:
% --------
% val = isopen (mongodbconn)
%
% Copyright 2017 The MathWorks, Inc.
% MONGODBCONN should be SCALAR
validateattributes(mongodbconn,"mongo",{"scalar"});
if ~isvalid(mongodbconn)
val = false;
return;
end
if isempty(getConnHandle(mongodbconn))
val = false;
return;
end
val = true;
end
function createCollection(mongodbconn,collectname,varargin)
%CREATECOLLECTION creates a new collection in database
%
% CREATECOLLECTION(MONGODBCONN,COLLECTNAME)
% creates a new collection in database.
%
% Input Arguments:
% ----------------
%
% MONGODBCONN - Mongo database object
% COLLECTNAME - Collection name
%
% Example:
% --------
%
% createCollection(dbconn,"product")
%
% Copyright 2017 The MathWorks, Inc.
if (exist('com.mongodb.BasicDBObject','class') ~= 8)
error(message('mongodb:mongodb:driverNotFound'));
end
p = inputParser;
p.addRequired("mongodbconn",@(x)validateattributes(x,"mongo",{"scalar"}));
p.addRequired("collectname",@(x)validateattributes(x,["string","char"],{"scalartext"}));
p.addParameter("Capped",false,@(x)validateattributes(x,"logical",{"scalar"}));
p.addParameter("Size",0,@(x)validateattributes(x,"numeric",{"nonempty","scalar","nonnegative"}));
p.addParameter("Max",0,@(x)validateattributes(x,"numeric",{"nonempty","scalar","nonnegative"}));
p.parse(mongodbconn,collectname,varargin{:});
% Check if Mongo Database Object is valid
if ~isopen(mongodbconn)
error(message('mongodb:mongodb:InvalidMongoConnection'));
end
collectname = char(p.Results.collectname);
capped = p.Results.Capped;
size = p.Results.Size;
max = p.Results.Max;
coll_exists = collectionexists(mongodbconn, collectname);
% If COLLECTION exists then no point in creating new collection
% with same name
if coll_exists
error(message('mongodb:mongodb:MongoCollectionExists',collectname));
end
try
databaseHandle = getDBHandle(mongodbconn);
options = com.mongodb.BasicDBObject();
options.put("capped",capped);
if size
options.put("size",size);
end
if max && size
options.put("max",max);
end
databaseHandle.createCollection(collectname,options);
catch e
error(message('mongodb:mongodb:DriverError',mongo.extractExceptionMessage(e)));
end
end
function dropCollection(mongodbconn,collectname)
%DROPCOLLECTION removes entire collection from database
%
% DROPCOLLECTION(MONGODBCONN,COLLECTNAME)
% drops entire collection from database
%
% Input Arguments:
% ----------------
% MONGODBCONN - Mongo database object
% COLLECTNAME - Collection name
%
% Example:
% --------
%
% dropCollection(dbconn,"product")
%
% Copyright 2017 The MathWorks, Inc.
p = inputParser;
p.addRequired("mongodbconn",@(x)validateattributes(x,"mongo",{"scalar"}));
p.addRequired("collectname",@(x)validateattributes(x,["string","char"],{"scalartext"}));
p.parse(mongodbconn,collectname);
% Check if Mongo Database Object is valid
if ~isopen(mongodbconn)
error(message('mongodb:mongodb:InvalidMongoConnection'));
end
collectname = char(p.Results.collectname);
coll_exists = collectionexists(mongodbconn, collectname);
% If COLLECTION exists then no point in creating new collection
% with same name
if ~coll_exists
error(message('mongodb:mongodb:NonExistentMongoCollection',collectname));
end
databaseHandle = getDBHandle(mongodbconn);
databaseHandle.getCollection(collectname).drop();
end
function val = count(mongodbconn,collectname,varargin)
%COUNT returns the total documents in a collection or a Mongo query
%
% VAL = COUNT(MONGODBCONN, COLLECTNAME)
% returns the count of all documents in a given COLLECTNAME
%
% VAL = COUNT(MONGODBCONN,COLLECTNAME,'NAME','VALUE')
% returns the count of documents with additional name-value
% arguments. For instance, you can check total documents for a
% Mongo Query against a collection.
%
% Input Arguments:
% ---------------
% MONGODBCONN - Mongo database object.
% COLLECTNAME - Collection name.
%
% Name-Value arguments:
% ---------------------
% Query - JSON-Style Mongo Query.
%
% Example:
% --------
%
% val = count(mongodbconn,"product")
%
% val = count(mongodbconn,"product","Query",'{"artist":"David"}')
%
% Copyright 2017 The MathWorks, Inc.
if (exist('com.mongodb.util.JSON','class') ~= 8)
error(message('mongodb:mongodb:driverNotFound'));
end
p = inputParser;
p.addRequired("mongodbconn",@(x)validateattributes(x,"mongo",{"scalar"}));
p.addRequired("collectname",@(x)validateattributes(x,["string","char"],{"scalartext"}));
p.addParameter("Query","",@(x)validateattributes(x,["string","char"],{"nonempty"}));
p.parse(mongodbconn,collectname,varargin{:});
query = char(strjoin(string(p.Results.Query), ''));
collectname = char(p.Results.collectname);
% Check if Mongo Database Object is valid
if ~isopen(mongodbconn)
error(message('mongodb:mongodb:InvalidMongoConnection'));
end
% Get the HANDLE to DATABASE object
databaseHandle = getDBHandle(mongodbconn);
% First check if a collection by the name COLLECTNAME exists in
% the DATABASE using Mongo-JAVA driver API COLLECTIONEXISTS
coll_exists = collectionexists(mongodbconn, collectname);
% If COLLECTION exists create a Mongo Collection Object
% else, return empty object with error message
if coll_exists
try
collectionHandle = databaseHandle.getCollection(collectname);
catch e
error(message('mongodb:mongodb:DriverError',mongo.extractExceptionMessage(e)))
end
else
error(message('mongodb:mongodb:NonExistentMongoCollection',collectname));
end
try
tic;
val = collectionHandle.count(com.mongodb.util.JSON.parse(query));
mongodbconn.QueryDuration = seconds(toc);
catch e
error(message('mongodb:mongodb:DriverError',mongo.extractExceptionMessage(e)))
end
end
function val = distinct(mongodbconn,collectname,fieldname,varargin)
%DISTINCT find distinct values for a specified field across a
%collection
%
% VAL = DISTINCT(MONGODBCONN,COLLECTNAME,FIELDNAME)
% returns distinct values in a field of a collection
%
% VAL = DISTINCT(MONGODBCONN,COLLECTNAME,FIELDNAME,'NAME','VALUE')
% returns distinct values in a field with additional name-value arguments.
% For instance, you can find distinct values in a field for a Mongo
% query executed against a collection
%
% Input arguments:
% ----------------
% MONGODBCONN - Mongo database object
% COLLECTNAME - Collection name
% FIELDNAME - Field name stored in a document of the collection
%
% Name-Value arguments:
% ---------------------
% Query - JSON-style Mongo Query.
%
% EXAMPLE:
% --------
%
% val = distinct(mongodbconn,"product","songs")
%
% val = distinct(mongodbconn,"product","songs","Query",'{"artist":"David"}')
%
% Copyright 2017 The MathWorks, Inc.
if (exist('com.mongodb.util.JSON','class') ~= 8 || ...
exist('com.mongodb.client.model.DBCollectionDistinctOptions','class') ~= 8 || ...
exist('com.mongodb.ReadPreference','class') ~= 8)
error(message('mongodb:mongodb:driverNotFound'));
end
p = inputParser;
p.addRequired("mongodbconn",@(x)validateattributes(x,"mongo",{"scalar"}));
p.addRequired("collectname",@(x)validateattributes(x,["string","char"],{"scalartext"}));
p.addRequired("fieldname",@(x)validateattributes(x,["string","char"],{"scalartext"}));
p.addParameter("Query","",@(x)validateattributes(x,["string","char"],{"nonempty"}));
p.addParameter("ReadPreference","",@(x)validateattributes(x,["string" "char"],{"scalartext"}));
p.parse(mongodbconn,collectname,fieldname,varargin{:});
collectname = char(p.Results.collectname);
fieldname = char(p.Results.fieldname);
query = char(strjoin(string(p.Results.Query), ''));
readpreference = char(p.Results.ReadPreference);
if ~isempty(readpreference)
readpreference = validatestring(readpreference,{'nearest','primary','secondary','primarypreferred','secondarypreferred'});
end
% Check if Mongo Database Object is valid
if ~isopen(mongodbconn)
error(message('mongodb:mongodb:InvalidMongoConnection'));
end
% Get the HANDLE to DATABASE object
databaseHandle = getDBHandle(mongodbconn);
% First check if a collection by the name COLLECTNAME exists in
% the DATABASE using Mongo-JAVA driver API COLLECTIONEXISTS
coll_exists = collectionexists(mongodbconn, collectname);
% If COLLECTION exists create a Mongo Collection Object
% else, return empty object with error message
if coll_exists
try
collectionHandle = databaseHandle.getCollection(collectname);
catch e
error(message('mongodb:mongodb:DriverError',mongo.extractExceptionMessage(e)))
end
else
error(message('mongodb:mongodb:NonExistentMongoCollection',collectname));
end
try
distinctoptions = com.mongodb.client.model.DBCollectionDistinctOptions;
if ~isempty(query)
distinctoptions = distinctoptions.filter(com.mongodb.util.JSON.parse(query));
end
if ~isempty(readpreference)
switch readpreference
case {'nearest'}
distinctoptions = distinctoptions.readPreference(com.mongodb.ReadPreference.nearest());
case {'primary'}
distinctoptions = distinctoptions.readPreference(com.mongodb.ReadPreference.primary());
case {'secondary'}
distinctoptions = distinctoptions.readPreference(com.mongodb.ReadPreference.secondary());
case {'primarypreferred'}
distinctoptions = distinctoptions.readPreference(com.mongodb.ReadPreference.primaryPreferred());
case {'secondarypreferred'}
distinctoptions = distinctoptions.readPreference(com.mongodb.ReadPreference.secondaryPreferred());
end
end
tic;
data = collectionHandle.distinct(fieldname,distinctoptions);
val = cell(data.toArray)';
mongodbconn.QueryDuration = seconds(toc);
catch e
error(message('mongodb:mongodb:DriverError',mongo.extractExceptionMessage(e)))
end
end
function documents = find(mongodbconn,collectname,varargin)
%FIND executes a MONGO QUERY on the database and retrieve documents
%
% DOCUMENTS = FIND(MONGODBCONN,COLLECTNAME)
% returns all documents in a collection
%
% DOCUMENTS = FIND(MONGODBCONN,COLLECTNAME,'NAME','VALUE')
% returns documents based on Name-Value arguments. For instance,
% you can specify a Mongo Query to filter documents.
%
% Input Arguments:
% ----------------
%
% MONGODBCONN - Mongo database object
% COLLECTNAME - Collection name
%
% Name-Value arguments:
% ---------------------
%
% Query A JSON-style MONGO Query used to
% filter documents in a collection and return
% only those who meets the criteria in Query
% E.g., {"artist": "David"}