MongoCollectionTest.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests\Mongo;
  3. use MongoDB\Driver\ReadPreference;
  4. use Alcaeus\MongoDbAdapter\Tests\TestCase;
  5. /**
  6. * @author alcaeus <alcaeus@alcaeus.org>
  7. */
  8. class MongoCollectionTest extends TestCase
  9. {
  10. public function testSerialize()
  11. {
  12. $this->assertInternalType('string', serialize($this->getCollection()));
  13. }
  14. public function testGetNestedCollections()
  15. {
  16. $collection = $this->getCollection()->foo->bar;
  17. $this->assertSame('mongo-php-adapter.test.foo.bar', (string) $collection);
  18. }
  19. public function testCreateRecord()
  20. {
  21. $collection = $this->getCollection();
  22. $expected = [
  23. 'ok' => 1.0,
  24. 'n' => 0,
  25. 'err' => null,
  26. 'errmsg' => null,
  27. ];
  28. $document = ['foo' => 'bar'];
  29. $this->assertSame($expected, $collection->insert($document));
  30. $this->assertInstanceOf('MongoId', $document['_id']);
  31. $id = (string) $document['_id'];
  32. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  33. $this->assertSame(1, $newCollection->count());
  34. $object = $newCollection->findOne();
  35. $this->assertNotNull($object);
  36. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  37. $this->assertSame($id, (string) $object->_id);
  38. $this->assertObjectHasAttribute('foo', $object);
  39. $this->assertAttributeSame('bar', 'foo', $object);
  40. }
  41. public function testInsertInvalidData()
  42. {
  43. $this->setExpectedException('PHPUnit_Framework_Error_Warning', 'MongoCollection::insert(): expects parameter 1 to be an array or object, integer given');
  44. $document = 8;
  45. $this->getCollection()->insert($document);
  46. }
  47. public function testInsertEmptyArray()
  48. {
  49. $document = [];
  50. $this->getCollection()->insert($document);
  51. $this->assertSame(1, $this->getCollection()->count());
  52. }
  53. public function testInsertArrayWithNumericKeys()
  54. {
  55. $document = [1 => 'foo'];
  56. $this->getCollection()->insert($document);
  57. $this->assertSame(1, $this->getCollection()->count(['_id' => $document['_id']]));
  58. }
  59. public function testInsertEmptyObject()
  60. {
  61. $document = (object) [];
  62. $this->getCollection()->insert($document);
  63. $this->assertSame(1, $this->getCollection()->count());
  64. }
  65. public function testInsertObjectWithPrivateProperties()
  66. {
  67. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  68. $document = new PrivatePropertiesStub();
  69. $this->getCollection()->insert($document);
  70. }
  71. public function testInsertWithInvalidKey()
  72. {
  73. $document = ['*' => 'foo'];
  74. $this->getCollection()->insert($document);
  75. $this->assertSame(1, $this->getCollection()->count(['*' => 'foo']));
  76. }
  77. public function testInsertWithEmptyKey()
  78. {
  79. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  80. $document = ['' => 'foo'];
  81. $this->getCollection()->insert($document);
  82. }
  83. public function testInsertWithNumericKey()
  84. {
  85. $document = ['foo'];
  86. $this->getCollection()->insert($document);
  87. $this->assertSame(1, $this->getCollection()->count(['foo']));
  88. }
  89. public function testInsertDuplicate()
  90. {
  91. $collection = $this->getCollection();
  92. $collection->createIndex(['foo' => 1], ['unique' => true]);
  93. $document = ['foo' => 'bar'];
  94. $collection->insert($document);
  95. unset($document['_id']);
  96. $this->setExpectedExceptionRegExp('MongoDuplicateKeyException', '/E11000 duplicate key error .* mongo-php-adapter\.test/');
  97. $collection->insert($document);
  98. }
  99. public function testUnacknowledgedWrite()
  100. {
  101. $document = ['foo' => 'bar'];
  102. $this->assertTrue($this->getCollection()->insert($document, ['w' => 0]));
  103. }
  104. public function testInsertWriteConcernException()
  105. {
  106. $this->setExpectedException(
  107. 'MongoWriteConcernException',
  108. "cannot use 'w' > 1 when a host is not replicated"
  109. );
  110. $document = ['foo' => 'bar'];
  111. $this->getCollection()->insert($document, ['w' => 2]);
  112. }
  113. public function testInsertMany()
  114. {
  115. $expected = [
  116. 'ok' => 1.0,
  117. 'n' => 0,
  118. 'syncMillis' => 0,
  119. 'writtenTo' => null,
  120. 'err' => null,
  121. ];
  122. $documents = [
  123. ['foo' => 'bar'],
  124. ['bar' => 'foo']
  125. ];
  126. $this->assertArraySubset($expected, $this->getCollection()->batchInsert($documents));
  127. foreach ($documents as $document) {
  128. $this->assertInstanceOf('MongoId', $document['_id']);
  129. }
  130. }
  131. public function testInsertManyWithNonNumericKeys()
  132. {
  133. $expected = [
  134. 'ok' => 1.0,
  135. 'n' => 0,
  136. 'syncMillis' => 0,
  137. 'writtenTo' => null,
  138. 'err' => null,
  139. ];
  140. $documents = [
  141. 'a' => ['foo' => 'bar'],
  142. 'b' => ['bar' => 'foo']
  143. ];
  144. $this->assertArraySubset($expected, $this->getCollection()->batchInsert($documents));
  145. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  146. $this->assertSame(2, $newCollection->count());
  147. }
  148. public function testBatchInsertContinuesOnError()
  149. {
  150. $expected = [
  151. 'ok' => 1.0,
  152. 'n' => 0,
  153. 'syncMillis' => 0,
  154. 'writtenTo' => null,
  155. 'err' => null,
  156. ];
  157. $documents = [
  158. 8,
  159. 'b' => ['bar' => 'foo']
  160. ];
  161. $this->assertArraySubset($expected, $this->getCollection()->batchInsert($documents, ['continueOnError' => true]));
  162. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  163. $this->assertSame(1, $newCollection->count());
  164. }
  165. public function testBatchInsertException()
  166. {
  167. $this->setExpectedExceptionRegExp('MongoDuplicateKeyException', '/E11000 duplicate key error .* mongo-php-adapter.test.*_id_/');
  168. $id = new \MongoId();
  169. $documents = [['_id' => $id, 'foo' => 'bar'], ['_id' => $id, 'foo' => 'bleh']];
  170. $this->getCollection()->batchInsert($documents);
  171. }
  172. public function testBatchInsertObjectWithPrivateProperties()
  173. {
  174. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  175. $documents = [new PrivatePropertiesStub()];
  176. $this->getCollection()->batchInsert($documents);
  177. }
  178. public function testBatchInsertWithInvalidKey()
  179. {
  180. $documents = [['*' => 'foo']];
  181. $this->getCollection()->batchInsert($documents);
  182. $this->assertSame(1, $this->getCollection()->count(['*' => 'foo']));
  183. }
  184. public function testBatchInsertWithEmptyKey()
  185. {
  186. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  187. $documents = [['' => 'foo']];
  188. $this->getCollection()->batchInsert($documents);
  189. }
  190. public function testBatchInsertWithNumericKey()
  191. {
  192. $documents = [['foo']];
  193. $this->getCollection()->batchInsert($documents);
  194. $this->assertSame(1, $this->getCollection()->count(['foo']));
  195. }
  196. public function testBatchInsertEmptyBatchException()
  197. {
  198. $this->setExpectedException('MongoException', 'No write ops were included in the batch');
  199. $documents = [];
  200. $this->getCollection()->batchInsert($documents, ['w' => 2]);
  201. }
  202. public function testUpdateWriteConcern()
  203. {
  204. $this->setExpectedException('MongoWriteConcernException', "cannot use 'w' > 1 when a host is not replicated");
  205. $this->getCollection()->update([], ['$set' => ['foo' => 'bar']], ['w' => 2]);
  206. }
  207. public function testUpdateOne()
  208. {
  209. $document = ['foo' => 'bar'];
  210. $this->getCollection()->insert($document);
  211. // Unset ID to re-insert
  212. unset($document['_id']);
  213. $this->getCollection()->insert($document);
  214. $expected = [
  215. 'ok' => 1.0,
  216. 'nModified' => 1,
  217. 'n' => 1,
  218. 'err' => null,
  219. 'errmsg' => null,
  220. 'updatedExisting' => true,
  221. ];
  222. $result = $this->getCollection()->update(['foo' => 'bar'], ['$set' => ['foo' => 'foo']]);
  223. $this->assertSame($expected, $result);
  224. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'foo']));
  225. }
  226. public function testUpdateReplaceOne()
  227. {
  228. $document = ['foo' => 'bar', 'bar' => 'foo'];
  229. $this->getCollection()->insert($document);
  230. // Unset ID to re-insert
  231. unset($document['_id']);
  232. $this->getCollection()->insert($document);
  233. $expected = [
  234. 'ok' => 1.0,
  235. 'nModified' => 1,
  236. 'n' => 1,
  237. 'err' => null,
  238. 'errmsg' => null,
  239. 'updatedExisting' => true,
  240. ];
  241. $result = $this->getCollection()->update(['foo' => 'bar'], ['foo' => 'foo']);
  242. $this->assertSame($expected, $result);
  243. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'foo']));
  244. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count(['bar' => 'foo']));
  245. }
  246. public function testUpdateReplaceMultiple()
  247. {
  248. $this->setExpectedExceptionRegExp('MongoWriteConcernException', '/multi update only works with \$ operators/', 9);
  249. $this->getCollection()->update(['foo' => 'bar'], ['foo' => 'foo'], ['multiple' => true]);
  250. }
  251. public function testUpdateDuplicate()
  252. {
  253. $collection = $this->getCollection();
  254. $collection->createIndex(['foo' => 1], ['unique' => 1]);
  255. $document = ['foo' => 'bar'];
  256. $collection->insert($document);
  257. $document = ['foo' => 'foo'];
  258. $collection->insert($document);
  259. $this->setExpectedException('MongoDuplicateKeyException');
  260. $collection->update(['foo' => 'bar'], ['$set' => ['foo' => 'foo']]);
  261. }
  262. public function testUpdateMany()
  263. {
  264. $document = ['change' => true, 'foo' => 'bar'];
  265. $this->getCollection()->insert($document);
  266. unset($document['_id']);
  267. $this->getCollection()->insert($document);
  268. $document = ['change' => true, 'foo' => 'foo'];
  269. $this->getCollection()->insert($document);
  270. $expected = [
  271. 'ok' => 1.0,
  272. 'nModified' => 2,
  273. 'n' => 3,
  274. 'err' => null,
  275. 'errmsg' => null,
  276. 'updatedExisting' => true,
  277. ];
  278. $result = $this->getCollection()->update(['change' => true], ['$set' => ['foo' => 'foo']], ['multiple' => true]);
  279. $this->assertSame($expected, $result);
  280. $this->assertSame(3, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'foo']));
  281. }
  282. public function testUnacknowledgedUpdate()
  283. {
  284. $document = ['foo' => 'bar'];
  285. $this->getCollection()->insert($document);
  286. unset($document['_id']);
  287. $this->getCollection()->insert($document);
  288. $this->assertTrue($this->getCollection()->update($document, ['$set' => ['foo' => 'foo']], ['w' => 0]));
  289. }
  290. public function testRemoveMultiple()
  291. {
  292. $document = ['change' => true, 'foo' => 'bar'];
  293. $this->getCollection()->insert($document);
  294. unset($document['_id']);
  295. $this->getCollection()->insert($document);
  296. $document = ['change' => true, 'foo' => 'foo'];
  297. $this->getCollection()->insert($document);
  298. $expected = [
  299. 'ok' => 1.0,
  300. 'n' => 2,
  301. 'err' => null,
  302. 'errmsg' => null,
  303. ];
  304. $result = $this->getCollection()->remove(['foo' => 'bar']);
  305. $this->assertSame($expected, $result);
  306. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count());
  307. }
  308. public function testRemoveSingle()
  309. {
  310. $document = ['change' => true, 'foo' => 'bar'];
  311. $this->getCollection()->insert($document);
  312. unset($document['_id']);
  313. $this->getCollection()->insert($document);
  314. unset($document['_id']);
  315. $this->getCollection()->insert($document);
  316. $expected = [
  317. 'ok' => 1.0,
  318. 'n' => 1,
  319. 'err' => null,
  320. 'errmsg' => null,
  321. ];
  322. $result = $this->getCollection()->remove(['foo' => 'bar'], ['justOne' => true]);
  323. $this->assertSame($expected, $result);
  324. $this->assertSame(2, $this->getCheckDatabase()->selectCollection('test')->count());
  325. }
  326. public function testRemoveUnacknowledged()
  327. {
  328. $document = ['change' => true, 'foo' => 'bar'];
  329. $this->getCollection()->insert($document);
  330. unset($document['_id']);
  331. $this->getCollection()->insert($document);
  332. unset($document['_id']);
  333. $this->getCollection()->insert($document);
  334. $this->assertTrue($this->getCollection()->remove(['foo' => 'bar'], ['w' => 0]));
  335. }
  336. public function testFindReturnsCursor()
  337. {
  338. $this->prepareData();
  339. $collection = $this->getCollection();
  340. $this->assertInstanceOf('MongoCursor', $collection->find());
  341. }
  342. public function testCount()
  343. {
  344. $this->prepareData();
  345. $collection = $this->getCollection();
  346. $this->assertSame(3, $collection->count());
  347. $this->assertSame(2, $collection->count(['foo' => 'bar']));
  348. }
  349. public function testCountWithLimit()
  350. {
  351. $this->prepareData();
  352. $collection = $this->getCollection();
  353. $this->assertSame(2, $collection->count([], ['limit' => 2]));
  354. $this->assertSame(1, $collection->count(['foo' => 'bar'], ['limit' => 1]));
  355. }
  356. public function testCountWithLimitLegacy()
  357. {
  358. $this->prepareData();
  359. $collection = $this->getCollection();
  360. $this->assertSame(2, $collection->count([], 2));
  361. $this->assertSame(1, $collection->count(['foo' => 'bar'], 1));
  362. }
  363. public function testCountWithSkip()
  364. {
  365. $this->prepareData();
  366. $collection = $this->getCollection();
  367. $this->assertSame(2, $collection->count([], ['skip' => 1]));
  368. $this->assertSame(1, $collection->count(['foo' => 'bar'], ['skip' => 1]));
  369. }
  370. public function testCountWithSkipLegacy()
  371. {
  372. $this->prepareData();
  373. $collection = $this->getCollection();
  374. $this->assertSame(2, $collection->count([], null, 1));
  375. $this->assertSame(1, $collection->count(['foo' => 'bar'], null, 1));
  376. }
  377. public function testCountWithLimitAndSkip()
  378. {
  379. $this->prepareData();
  380. $collection = $this->getCollection();
  381. $this->assertSame(2, $collection->count([], ['skip' => 1, 'limit' => 2]));
  382. $this->assertSame(1, $collection->count([], ['skip' => 1, 'limit' => 1]));
  383. }
  384. public function testCountWithLimitAndSkipLegacy()
  385. {
  386. $this->prepareData();
  387. $collection = $this->getCollection();
  388. $this->assertSame(2, $collection->count([], 2, 1));
  389. $this->assertSame(1, $collection->count([], 1, 1));
  390. }
  391. public function testCountTimeout()
  392. {
  393. $this->failMaxTimeMS();
  394. $this->setExpectedException('MongoExecutionTimeoutException');
  395. $this->getCollection()->count([], ['maxTimeMS' => 1]);
  396. }
  397. public function testFindOne()
  398. {
  399. $this->prepareData();
  400. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
  401. $this->assertSame(['foo' => 'foo'], $document);
  402. }
  403. public function testFindOneNotFound()
  404. {
  405. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
  406. $this->assertNull($document);
  407. }
  408. public function testFindOneConnectionIssue()
  409. {
  410. $this->setExpectedException('MongoConnectionException');
  411. $client = $this->getClient([], 'mongodb://localhost:28888?connectTimeoutMS=1');
  412. $collection = $client->selectCollection('mongo-php-adapter', 'test');
  413. $collection->findOne();
  414. }
  415. public function testDistinct()
  416. {
  417. $this->prepareData();
  418. $values = $this->getCollection()->distinct('foo');
  419. $this->assertInternalType('array', $values);
  420. sort($values);
  421. $this->assertEquals(['bar', 'foo'], $values);
  422. }
  423. public function testDistinctWithQuery()
  424. {
  425. $this->prepareData();
  426. $values = $this->getCollection()->distinct('foo', ['foo' => 'bar']);
  427. $this->assertInternalType('array', $values);
  428. $this->assertEquals(['bar'], $values);
  429. }
  430. public function testDistinctWithIdQuery()
  431. {
  432. $document1 = ['foo' => 'bar'];
  433. $document2 = ['foo' => 'bar'];
  434. $document3 = ['foo' => 'foo'];
  435. $collection = $this->getCollection();
  436. $collection->insert($document1);
  437. $collection->insert($document2);
  438. $collection->insert($document3);
  439. $this->assertSame(
  440. ['bar'],
  441. $collection->distinct('foo', ['_id' => [
  442. '$in' => [$document1['_id'], $document2['_id']]
  443. ]])
  444. );
  445. $this->assertEquals(
  446. ['bar', 'foo'],
  447. $collection->distinct('foo', ['_id' => [
  448. '$in' => [$document1['_id'], $document3['_id']]
  449. ]])
  450. );
  451. }
  452. public function testAggregate()
  453. {
  454. $collection = $this->getCollection();
  455. $this->prepareData();
  456. $pipeline = [
  457. [
  458. '$group' => [
  459. '_id' => '$foo',
  460. 'count' => [ '$sum' => 1 ],
  461. ],
  462. ],
  463. [
  464. '$sort' => ['_id' => 1]
  465. ]
  466. ];
  467. $result = $collection->aggregate($pipeline);
  468. $this->assertInternalType('array', $result);
  469. $this->assertArrayHasKey('result', $result);
  470. $this->assertEquals([
  471. ['_id' => 'bar', 'count' => 2],
  472. ['_id' => 'foo', 'count' => 1],
  473. ], $result['result']);
  474. }
  475. public function testAggregateWithMultiplePilelineOperatorsAsArguments()
  476. {
  477. $collection = $this->getCollection();
  478. $this->prepareData();
  479. try {
  480. $result = $collection->aggregate(
  481. [
  482. '$group' => [
  483. '_id' => '$foo',
  484. 'count' => [ '$sum' => 1 ],
  485. ],
  486. ],
  487. [
  488. '$sort' => ['_id' => 1]
  489. ]
  490. );
  491. } catch (\MongoResultException $ex) {
  492. $msg = 'MongoCollection::aggregate ( array $op [, array $op [, array $... ]] ) should accept variable amount of pipeline operators as argument'
  493. . "\n"
  494. . $ex;
  495. $this->fail($msg);
  496. }
  497. $this->assertInternalType('array', $result);
  498. $this->assertArrayHasKey('result', $result);
  499. $this->assertEquals([
  500. ['_id' => 'bar', 'count' => 2],
  501. ['_id' => 'foo', 'count' => 1],
  502. ], $result['result']);
  503. }
  504. public function testAggregateInvalidPipeline()
  505. {
  506. $collection = $this->getCollection();
  507. $pipeline = [
  508. [
  509. '$invalid' => []
  510. ],
  511. ];
  512. $this->setExpectedException('MongoResultException', 'Unrecognized pipeline stage name');
  513. $collection->aggregate($pipeline);
  514. }
  515. public function testAggregateTimeoutException()
  516. {
  517. $collection = $this->getCollection();
  518. $this->failMaxTimeMS();
  519. $this->setExpectedException('MongoExecutionTimeoutException');
  520. $pipeline = [
  521. [
  522. '$group' => [
  523. '_id' => '$foo',
  524. 'count' => [ '$sum' => 1 ],
  525. ],
  526. ],
  527. [
  528. '$sort' => ['_id' => 1]
  529. ]
  530. ];
  531. $collection->aggregate($pipeline, ['maxTimeMS' => 1]);
  532. }
  533. public function testAggregateCursor()
  534. {
  535. $collection = $this->getCollection();
  536. $this->prepareData();
  537. $pipeline = [
  538. [
  539. '$group' => [
  540. '_id' => '$foo',
  541. 'count' => [ '$sum' => 1 ],
  542. ],
  543. ],
  544. [
  545. '$sort' => ['_id' => 1]
  546. ]
  547. ];
  548. $cursor = $collection->aggregateCursor($pipeline);
  549. $this->assertInstanceOf('MongoCommandCursor', $cursor);
  550. $this->assertEquals([
  551. ['_id' => 'bar', 'count' => 2],
  552. ['_id' => 'foo', 'count' => 1],
  553. ], iterator_to_array($cursor));
  554. }
  555. public function testReadPreference()
  556. {
  557. $collection = $this->getCollection();
  558. $this->assertSame(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  559. $this->assertFalse($collection->getSlaveOkay());
  560. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  561. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  562. $this->assertTrue($collection->getSlaveOkay());
  563. $this->assertTrue($collection->setSlaveOkay(true));
  564. $this->assertSame(['type' => \MongoClient::RP_SECONDARY_PREFERRED, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  565. $this->assertTrue($collection->setSlaveOkay(false));
  566. $this->assertArraySubset(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  567. }
  568. public function testReadPreferenceIsSetInDriver()
  569. {
  570. $this->skipTestIf(extension_loaded('mongo'));
  571. $collection = $this->getCollection();
  572. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  573. // Only way to check whether options are passed down is through debugInfo
  574. $readPreference = $collection->getCollection()->__debugInfo()['readPreference'];
  575. $this->assertSame(ReadPreference::RP_SECONDARY, $readPreference->getMode());
  576. $this->assertSame([['a' => 'b']], $readPreference->getTagSets());
  577. }
  578. public function testReadPreferenceIsInherited()
  579. {
  580. $database = $this->getDatabase();
  581. $database->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]);
  582. $collection = $database->selectCollection('test');
  583. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  584. }
  585. public function testWriteConcern()
  586. {
  587. $collection = $this->getCollection();
  588. $this->assertTrue($collection->setWriteConcern('majority', 100));
  589. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  590. }
  591. public function testWriteConcernIsSetInDriver()
  592. {
  593. $this->skipTestIf(extension_loaded('mongo'));
  594. $collection = $this->getCollection();
  595. $this->assertTrue($collection->setWriteConcern(2, 100));
  596. // Only way to check whether options are passed down is through debugInfo
  597. $writeConcern = $collection->getCollection()->__debugInfo()['writeConcern'];
  598. $this->assertSame(2, $writeConcern->getW());
  599. $this->assertSame(100, $writeConcern->getWtimeout());
  600. }
  601. public function testWriteConcernIsInherited()
  602. {
  603. $database = $this->getDatabase();
  604. $database->setWriteConcern('majority', 100);
  605. $collection = $database->selectCollection('test');
  606. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  607. }
  608. public function testSaveInsert()
  609. {
  610. $id = '54203e08d51d4a1f868b456e';
  611. $collection = $this->getCollection();
  612. $objectId = new \MongoId($id);
  613. $expected = [
  614. 'ok' => 1.0,
  615. 'nModified' => 0,
  616. 'n' => 1,
  617. 'err' => null,
  618. 'errmsg' => null,
  619. 'upserted' => $objectId,
  620. 'updatedExisting' => false,
  621. ];
  622. $document = ['_id' => $objectId, 'foo' => 'bar'];
  623. $this->assertEquals($expected, $collection->save($document));
  624. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  625. $this->assertSame(1, $newCollection->count());
  626. $object = $newCollection->findOne();
  627. $this->assertNotNull($object);
  628. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  629. $this->assertSame($id, (string) $object->_id);
  630. $this->assertObjectHasAttribute('foo', $object);
  631. $this->assertAttributeSame('bar', 'foo', $object);
  632. }
  633. public function testRemoveOne()
  634. {
  635. $id = '54203e08d51d4a1f868b456e';
  636. $collection = $this->getCollection();
  637. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  638. $collection->insert($document);
  639. $collection->remove(['_id' => new \MongoId($id)]);
  640. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  641. $this->assertSame(0, $newCollection->count());
  642. }
  643. public function testSaveUpdate()
  644. {
  645. $expected = [
  646. 'ok' => 1.0,
  647. 'nModified' => 1,
  648. 'n' => 1,
  649. 'err' => null,
  650. 'errmsg' => null,
  651. 'updatedExisting' => true,
  652. ];
  653. $id = '54203e08d51d4a1f868b456e';
  654. $collection = $this->getCollection();
  655. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  656. $saveDocument = ['_id' => new \MongoId($id), 'foo' => 'foo'];
  657. $collection->insert($insertDocument);
  658. $this->assertSame($expected, $collection->save($saveDocument));
  659. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  660. $this->assertSame(1, $newCollection->count());
  661. $object = $newCollection->findOne();
  662. $this->assertNotNull($object);
  663. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  664. $this->assertSame($id, (string) $object->_id);
  665. $this->assertObjectHasAttribute('foo', $object);
  666. $this->assertAttributeSame('foo', 'foo', $object);
  667. }
  668. public function testSavingShouldReplaceTheWholeDocument() {
  669. $id = '54203e08d51d4a1f868b456e';
  670. $collection = $this->getCollection();
  671. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  672. $saveDocument = ['_id' => new \MongoId($id)];
  673. $collection->insert($insertDocument);
  674. $collection->save($saveDocument);
  675. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  676. $this->assertSame(1, $newCollection->count());
  677. $object = $newCollection->findOne();
  678. $this->assertNotNull($object);
  679. $this->assertObjectNotHasAttribute('foo', $object);
  680. }
  681. public function testSaveDuplicate()
  682. {
  683. $collection = $this->getCollection();
  684. $collection->createIndex(['foo' => 1], ['unique' => true]);
  685. $document = ['foo' => 'bar'];
  686. $collection->save($document);
  687. $this->setExpectedException('MongoDuplicateKeyException');
  688. unset($document['_id']);
  689. $collection->save($document);
  690. }
  691. public function testSaveEmptyKeys()
  692. {
  693. $document = [];
  694. $this->getCollection()->save($document);
  695. $this->assertSame(1, $this->getCollection()->count());
  696. }
  697. public function testSaveEmptyObject()
  698. {
  699. $document = (object) [];
  700. $this->getCollection()->save($document);
  701. $this->assertSame(1, $this->getCollection()->count());
  702. }
  703. public function testGetDBRef()
  704. {
  705. $collection = $this->getCollection();
  706. $insertDocument = ['_id' => 1, 'foo' => 'bar'];
  707. $collection->insert($insertDocument);
  708. $document = $collection->getDBRef([
  709. '$ref' => 'test',
  710. '$id' => 1,
  711. ]);
  712. $this->assertEquals($insertDocument, $document);
  713. }
  714. public function testCreateDBRef()
  715. {
  716. $collection = $this->getCollection();
  717. $reference = $collection->createDBRef(['_id' => 'foo']);
  718. $this->assertSame(
  719. [
  720. '$ref' => 'test',
  721. '$id' => 'foo',
  722. ],
  723. $reference
  724. );
  725. }
  726. public function testCreateIndex()
  727. {
  728. $expected = [
  729. 'createdCollectionAutomatically' => true,
  730. 'numIndexesBefore' => 1,
  731. 'numIndexesAfter' => 2,
  732. 'ok' => 1.0,
  733. ];
  734. $collection = $this->getCollection();
  735. $this->assertSame($expected, $collection->createIndex(['foo' => 1]));
  736. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  737. $iterator = $newCollection->listIndexes();
  738. $indexes = iterator_to_array($iterator);
  739. $this->assertCount(2, $indexes);
  740. $index = $indexes[1];
  741. $this->assertSame(['foo' => 1], $index->getKey());
  742. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  743. }
  744. public function testCreateIndexInvalid()
  745. {
  746. $this->setExpectedException('MongoException', 'index specification has no elements');
  747. $this->getCollection()->createIndex([]);
  748. }
  749. public function testCreateIndexTwice()
  750. {
  751. $this->getCollection()->createIndex(['foo' => 1]);
  752. $expected = [
  753. 'createdCollectionAutomatically' => false,
  754. 'numIndexesBefore' => 2,
  755. 'numIndexesAfter' => 2,
  756. 'note' => 'all indexes already exist',
  757. 'ok' => 1.0
  758. ];
  759. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  760. }
  761. public function testCreateIndexWithDeprecatedOptions()
  762. {
  763. $this->getCollection()->createIndex(['foo' => 1], ['w' => 1]);
  764. $expected = [
  765. 'createdCollectionAutomatically' => false,
  766. 'numIndexesBefore' => 2,
  767. 'numIndexesAfter' => 2,
  768. 'note' => 'all indexes already exist',
  769. 'ok' => 1.0
  770. ];
  771. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  772. }
  773. public function testCreateIndexTwiceWithSameName()
  774. {
  775. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  776. $expected = [
  777. 'createdCollectionAutomatically' => false,
  778. 'numIndexesBefore' => 2,
  779. 'numIndexesAfter' => 2,
  780. 'note' => 'all indexes already exist',
  781. 'ok' => 1.0
  782. ];
  783. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']));
  784. }
  785. public function testCreateIndexTwiceWithDifferentName()
  786. {
  787. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  788. $expected = [
  789. 'createdCollectionAutomatically' => false,
  790. 'numIndexesBefore' => 2,
  791. 'numIndexesAfter' => 2,
  792. 'note' => 'all indexes already exist',
  793. 'ok' => 1.0
  794. ];
  795. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'index_test']));
  796. }
  797. public function testCreateIndexTwiceWithDifferentOrder()
  798. {
  799. $this->getCollection()->createIndex(['foo' => 1, 'bar' => 1]);
  800. $expected = [
  801. 'createdCollectionAutomatically' => false,
  802. 'numIndexesBefore' => 2,
  803. 'numIndexesAfter' => 3,
  804. 'ok' => 1.0
  805. ];
  806. $this->assertSame($expected, $this->getCollection()->createIndex(['bar' => 1, 'foo' => 1]));
  807. }
  808. public function testCreateIndexesWithDifferentOptions()
  809. {
  810. $this->setExpectedException('MongoResultException');
  811. $this->getCollection()->createIndex(['foo' => 1]);
  812. $this->getCollection()->createIndex(['foo' => 1], ['unique' => true]);
  813. }
  814. /**
  815. * @dataProvider createIndexIgnoredOptions
  816. */
  817. public function testCreateIndexesWithIgnoredOptions($option)
  818. {
  819. $this->getCollection()->createIndex(['foo' => 1]);
  820. $expected = [
  821. 'createdCollectionAutomatically' => false,
  822. 'numIndexesBefore' => 2,
  823. 'numIndexesAfter' => 2,
  824. 'note' => 'all indexes already exist',
  825. 'ok' => 1.0
  826. ];
  827. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], [$option => true]));
  828. }
  829. public static function createIndexIgnoredOptions()
  830. {
  831. return [
  832. 'background' => ['background'],
  833. 'dropDups' => ['dropDups'],
  834. ];
  835. }
  836. public function testCreateIndexWithSameNameAndDifferentOptions()
  837. {
  838. $this->setExpectedException('MongoResultException');
  839. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'foo']);
  840. $this->getCollection()->createIndex(['bar' => 1], ['name' => 'foo']);
  841. }
  842. public function testEnsureIndex()
  843. {
  844. $expected = [
  845. 'createdCollectionAutomatically' => true,
  846. 'numIndexesBefore' => 1,
  847. 'numIndexesAfter' => 2,
  848. 'ok' => 1.0
  849. ];
  850. $collection = $this->getCollection();
  851. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  852. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  853. $indexes = iterator_to_array($newCollection->listIndexes());
  854. $this->assertCount(2, $indexes);
  855. $index = $indexes[1];
  856. $this->assertSame(['bar' => 1], $index->getKey());
  857. $this->assertTrue($index->isUnique());
  858. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  859. }
  860. public function testEnsureIndexAlreadyExists()
  861. {
  862. $collection = $this->getCollection();
  863. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  864. $expected = [
  865. 'createdCollectionAutomatically' => false,
  866. 'numIndexesBefore' => 2,
  867. 'numIndexesAfter' => 2,
  868. 'ok' => 1.0,
  869. 'note' => 'all indexes already exist',
  870. ];
  871. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  872. }
  873. public function testEnsureIndexAlreadyExistsWithDifferentOptions()
  874. {
  875. $collection = $this->getCollection();
  876. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  877. $this->setExpectedException('MongoResultException', 'Index with name: bar_1 already exists with different options');
  878. $collection->ensureIndex(['bar' => 1]);
  879. }
  880. public function testDeleteIndexUsingIndexName()
  881. {
  882. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  883. $newCollection->createIndex(['bar' => 1], ['name' => 'bar']);
  884. $expected = [
  885. 'nIndexesWas' => 2,
  886. 'errmsg' => 'index not found with name [bar_1]',
  887. 'ok' => 0.0,
  888. 'code' => 27,
  889. ];
  890. $this->assertEquals($expected, $this->getCollection()->deleteIndex('bar'));
  891. $this->assertCount(2, iterator_to_array($newCollection->listIndexes()));
  892. }
  893. public function testDeleteIndexUsingField()
  894. {
  895. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  896. $newCollection->createIndex(['bar' => 1]);
  897. $expected = [
  898. 'nIndexesWas' => 2,
  899. 'ok' => 1.0,
  900. ];
  901. $this->assertSame($expected, $this->getCollection()->deleteIndex('bar'));
  902. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  903. }
  904. public function testDeleteIndexUsingKeys()
  905. {
  906. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  907. $newCollection->createIndex(['bar' => 1]);
  908. $expected = [
  909. 'nIndexesWas' => 2,
  910. 'ok' => 1.0,
  911. ];
  912. $this->assertSame($expected, $this->getcollection()->deleteIndex(['bar' => 1]));
  913. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  914. }
  915. public function testDeleteIndexes()
  916. {
  917. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  918. $newCollection->createIndex(['bar' => 1]);
  919. $expected = [
  920. 'nIndexesWas' => 2,
  921. 'msg' => 'non-_id indexes dropped for collection',
  922. 'ok' => 1.0,
  923. ];
  924. $this->assertSame($expected, $this->getcollection()->deleteIndexes());
  925. $this->assertCount(1, iterator_to_array($newCollection->listIndexes())); // ID index is present by default
  926. }
  927. public function testDeleteIndexesForNonExistingCollection()
  928. {
  929. $expected = [
  930. 'ok' => 0.0,
  931. 'errmsg' => 'ns not found',
  932. 'code' => 26,
  933. ];
  934. $this->assertSame($expected, $this->getcollection('nonExisting')->deleteIndexes());
  935. }
  936. public function testGetIndexInfo()
  937. {
  938. $collection = $this->getCollection();
  939. $collection->createIndex(['foo' => 1]);
  940. $collection->createIndex(['bar' => 1], ['unique' => true]);
  941. $expected = [
  942. [
  943. 'v' => 1,
  944. 'key' => ['_id' => 1],
  945. 'name' => '_id_',
  946. 'ns' => 'mongo-php-adapter.test',
  947. ],
  948. [
  949. 'v' => 1,
  950. 'key' => ['foo' => 1],
  951. 'name' => 'foo_1',
  952. 'ns' => 'mongo-php-adapter.test',
  953. ],
  954. [
  955. 'v' => 1,
  956. 'key' => ['bar' => 1],
  957. 'name' => 'bar_1',
  958. 'ns' => 'mongo-php-adapter.test',
  959. 'unique' => true,
  960. ],
  961. ];
  962. $this->assertEquals(
  963. $expected,
  964. $collection->getIndexInfo()
  965. );
  966. }
  967. public function testFindAndModifyUpdate()
  968. {
  969. $id = '54203e08d51d4a1f868b456e';
  970. $collection = $this->getCollection();
  971. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  972. $collection->insert($document);
  973. $document = $collection->findAndModify(
  974. ['_id' => new \MongoId($id)],
  975. ['$set' => ['foo' => 'foo']]
  976. );
  977. $this->assertSame('bar', $document['foo']);
  978. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  979. $this->assertSame(1, $newCollection->count());
  980. $object = $newCollection->findOne();
  981. $this->assertNotNull($object);
  982. $this->assertAttributeSame('foo', 'foo', $object);
  983. }
  984. public function testFindAndModifyUpdateWithUpdateOptions()
  985. {
  986. $id = '54203e08d51d4a1f868b456e';
  987. $collection = $this->getCollection();
  988. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  989. $collection->insert($document);
  990. $document = $collection->findAndModify(
  991. ['_id' => new \MongoId($id)],
  992. [],
  993. [],
  994. [
  995. 'update' => ['bar' => 'foo']
  996. ]
  997. );
  998. $this->assertSame('bar', $document['foo']);
  999. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1000. $this->assertSame(1, $newCollection->count());
  1001. $object = $newCollection->findOne();
  1002. $this->assertNotNull($object);
  1003. $this->assertAttributeSame('foo', 'bar', $object);
  1004. $this->assertObjectNotHasAttribute('foo', $object);
  1005. }
  1006. public function testFindAndModifyWithUpdateParamAndOption()
  1007. {
  1008. $id = '54203e08d51d4a1f868b456e';
  1009. $collection = $this->getCollection();
  1010. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1011. $collection->insert($document);
  1012. $data = ['foo' => 'foo', 'bar' => 'bar'];
  1013. $this->getCollection()->findAndModify(
  1014. ['_id' => new \MongoId($id)],
  1015. [$data],
  1016. [],
  1017. [
  1018. 'update' => ['$set' => ['foo' => 'foobar']],
  1019. 'upsert' => true,
  1020. ]
  1021. );
  1022. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1023. $this->assertSame(1, $newCollection->count());
  1024. $object = $newCollection->findOne();
  1025. $this->assertNotNull($object);
  1026. $this->assertAttributeSame('foobar', 'foo', $object);
  1027. $this->assertObjectNotHasAttribute('bar', $object);
  1028. }
  1029. public function testFindAndModifyUpdateReplace()
  1030. {
  1031. $id = '54203e08d51d4a1f868b456e';
  1032. $collection = $this->getCollection();
  1033. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1034. $collection->insert($document);
  1035. $document = $collection->findAndModify(
  1036. ['_id' => new \MongoId($id)],
  1037. ['_id' => new \MongoId($id), 'foo' => 'boo']
  1038. );
  1039. $this->assertSame('bar', $document['foo']);
  1040. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1041. $this->assertSame(1, $newCollection->count());
  1042. $object = $newCollection->findOne();
  1043. $this->assertNotNull($object);
  1044. $this->assertAttributeSame('boo', 'foo', $object);
  1045. $this->assertObjectNotHasAttribute('bar', $object);
  1046. }
  1047. public function testFindAndModifyUpdateReturnNew()
  1048. {
  1049. $id = '54203e08d51d4a1f868b456e';
  1050. $collection = $this->getCollection();
  1051. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1052. $collection->insert($document);
  1053. $document = $collection->findAndModify(
  1054. ['_id' => new \MongoId($id)],
  1055. ['$set' => ['foo' => 'foo']],
  1056. null,
  1057. ['new' => true]
  1058. );
  1059. $this->assertSame('foo', $document['foo']);
  1060. }
  1061. public function testFindAndModifyWithFields()
  1062. {
  1063. $id = '54203e08d51d4a1f868b456e';
  1064. $collection = $this->getCollection();
  1065. $document = [
  1066. '_id' => new \MongoId($id),
  1067. 'foo' => 'bar',
  1068. 'bar' => 'foo',
  1069. ];
  1070. $collection->insert($document);
  1071. $document = $collection->findAndModify(
  1072. ['_id' => new \MongoId($id)],
  1073. ['$set' => ['foo' => 'foo']],
  1074. ['foo' => true]
  1075. );
  1076. $this->assertArrayNotHasKey('bar', $document);
  1077. $this->assertArrayHasKey('foo', $document);
  1078. }
  1079. public function testGroup()
  1080. {
  1081. $collection = $this->getCollection();
  1082. $document1 = ['a' => 2];
  1083. $collection->insert($document1);
  1084. $document2 = ['b' => 5];
  1085. $collection->insert($document2);
  1086. $document3 = ['a' => 1];
  1087. $collection->insert($document3);
  1088. $keys = [];
  1089. $initial = ["count" => 0];
  1090. $reduce = "function (obj, prev) { prev.count++; }";
  1091. $condition = ['condition' => ["a" => [ '$gt' => 1]]];
  1092. $result = $collection->group($keys, $initial, $reduce, $condition);
  1093. $this->assertArraySubset(
  1094. [
  1095. 'retval' => [['count' => 1.0]],
  1096. 'count' => 1.0,
  1097. 'keys' => 1,
  1098. 'ok' => 1.0,
  1099. ],
  1100. $result
  1101. );
  1102. }
  1103. public function testMapReduce()
  1104. {
  1105. $data = array(
  1106. array(
  1107. 'username' => 'jones',
  1108. 'likes' => 20.0,
  1109. 'text' => 'Hello world!'
  1110. ),
  1111. array(
  1112. 'username' => 'bob',
  1113. 'likes' => 100.0,
  1114. 'text' => 'Hello world!'
  1115. ),
  1116. array(
  1117. 'username' => 'bob',
  1118. 'likes' => 100.0,
  1119. 'text' => 'Hello world!'
  1120. ),
  1121. );
  1122. $collection = $this->getCollection();
  1123. $collection->batchInsert($data);
  1124. $map = 'function() {
  1125. emit(this.username, { count: 1, likes: this.likes });
  1126. }';
  1127. $reduce = 'function(key, values) {
  1128. var result = {count: 0, likes: 0};
  1129. values.forEach(function(value) {
  1130. result.count += value.count;
  1131. result.likes += value.likes;
  1132. });
  1133. return result;
  1134. }';
  1135. $finalize = 'function (key, value) { value.test = "test"; return value; }';
  1136. $command = [
  1137. 'mapreduce' => $this->getCollection()->getName(),
  1138. 'map' => new \MongoCode($map),
  1139. 'reduce' => new \MongoCode($reduce),
  1140. 'query' => (object) [],
  1141. 'out' => ['inline' => true],
  1142. 'finalize' => new \MongoCode($finalize),
  1143. ];
  1144. $result = $this->getDatabase()->command($command);
  1145. $expected = [
  1146. [
  1147. '_id' => 'bob',
  1148. 'value' => [
  1149. 'count' => 2.0,
  1150. 'likes' => 200.0,
  1151. 'test' => 'test',
  1152. ],
  1153. ],
  1154. [
  1155. '_id' => 'jones',
  1156. 'value' => [
  1157. 'count' => 1.0,
  1158. 'likes' => 20.0,
  1159. 'test' => 'test',
  1160. ],
  1161. ],
  1162. ];
  1163. $this->assertSame(1.0, $result['ok']);
  1164. $this->assertSame($expected, $result['results']);
  1165. }
  1166. public function testFindAndModifyResultException()
  1167. {
  1168. $this->markTestSkipped('Test fails on travis-ci - skipped while investigating this');
  1169. $collection = $this->getCollection();
  1170. $this->setExpectedException('MongoResultException');
  1171. $collection->findAndModify(
  1172. array("inprogress" => false, "name" => "Next promo"),
  1173. array('$unsupportedOperator' => array("tasks" => -1)),
  1174. array("tasks" => true),
  1175. array("new" => true)
  1176. );
  1177. }
  1178. public function testFindAndModifyExceptionTimeout()
  1179. {
  1180. $this->failMaxTimeMS();
  1181. $id = '54203e08d51d4a1f868b456e';
  1182. $collection = $this->getCollection();
  1183. $this->setExpectedException('MongoExecutionTimeoutException');
  1184. $document = $collection->findAndModify(
  1185. ['_id' => new \MongoId($id)],
  1186. null,
  1187. null,
  1188. ['maxTimeMS' => 1, 'remove' => true]
  1189. );
  1190. }
  1191. public function testFindAndModifyRemove()
  1192. {
  1193. $id = '54203e08d51d4a1f868b456e';
  1194. $collection = $this->getCollection();
  1195. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1196. $collection->insert($document);
  1197. $document = $collection->findAndModify(
  1198. ['_id' => new \MongoId($id)],
  1199. null,
  1200. null,
  1201. ['remove' => true]
  1202. );
  1203. $this->assertEquals('bar', $document['foo']);
  1204. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1205. $this->assertSame(0, $newCollection->count());
  1206. }
  1207. public function testValidate()
  1208. {
  1209. $collection = $this->getCollection();
  1210. $document = ['foo' => 'bar'];
  1211. $collection->insert($document);
  1212. $result = $collection->validate();
  1213. $this->assertArraySubset(
  1214. [
  1215. 'ns' => 'mongo-php-adapter.test',
  1216. 'nrecords' => 1,
  1217. 'nIndexes' => 1,
  1218. 'keysPerIndex' => ['mongo-php-adapter.test.$_id_' => 1],
  1219. 'valid' => true,
  1220. 'errors' => [],
  1221. 'warning' => 'Some checks omitted for speed. use {full:true} option to do more thorough scan.',
  1222. 'ok' => 1.0
  1223. ],
  1224. $result
  1225. );
  1226. }
  1227. public function testDrop()
  1228. {
  1229. $document = ['foo' => 'bar'];
  1230. $this->getCollection()->insert($document);
  1231. $expected = [
  1232. 'ns' => (string) $this->getCollection(),
  1233. 'nIndexesWas' => 1,
  1234. 'ok' => 1.0
  1235. ];
  1236. $this->assertSame($expected, $this->getCollection()->drop());
  1237. }
  1238. public function testEmptyCollectionName()
  1239. {
  1240. $this->setExpectedException('Exception', 'Collection name cannot be empty');
  1241. new \MongoCollection($this->getDatabase(), '');
  1242. }
  1243. public function testSelectCollectionWithNullBytes()
  1244. {
  1245. $this->setExpectedException('Exception', 'Collection name cannot contain null bytes');
  1246. new \MongoCollection($this->getDatabase(), 'foo' . chr(0));
  1247. }
  1248. public function testSubCollectionWithNullBytes()
  1249. {
  1250. $collection = $this->getCollection();
  1251. $this->assertInstanceOf('MongoCollection', $collection->{'foo' . chr(0)});
  1252. $this->assertSame('test', $collection->getName());
  1253. }
  1254. public function testSelectCollectionWithDatabaseObject()
  1255. {
  1256. $client = $this->getClient();
  1257. $database = $this->getDatabase($client);
  1258. $collection = $client->selectCollection($database, 'test');
  1259. $this->assertSame('mongo-php-adapter.test', (string) $collection);
  1260. }
  1261. public function testHasNextLoop()
  1262. {
  1263. $collection = $this->getCollection();
  1264. for ($i = 0; $i < 5; $i++) {
  1265. $document = ['i' => $i];
  1266. $collection->insert($document);
  1267. }
  1268. $cursor = $collection->find()->sort(['i' => 1]);
  1269. $data = [];
  1270. $i = 0;
  1271. while ($cursor->hasNext()) {
  1272. $this->assertSame($i < 5, $cursor->hasNext());
  1273. $row = $cursor->getNext();
  1274. $this->assertSame($i, $row['i']);
  1275. $data[] = $row;
  1276. $i++;
  1277. }
  1278. $this->assertCount(5, $data);
  1279. }
  1280. public function testProjectionWithBSONTypes()
  1281. {
  1282. $collection = $this->getCollection();
  1283. $id = new \MongoId();
  1284. $referencedId = new \MongoId();
  1285. $data = [
  1286. '_id' => $id,
  1287. 'loveItems' => [
  1288. [
  1289. 'sellable' => [
  1290. '$ref' => 'sellables',
  1291. '$id' => $referencedId,
  1292. ]
  1293. ],
  1294. [
  1295. 'sellable' => [
  1296. '$ref' => 'sellables',
  1297. '$id' => new \MongoId(),
  1298. ]
  1299. ]
  1300. ]
  1301. ];
  1302. $collection->insert($data);
  1303. $item = $collection->findOne(
  1304. ['_id' => $id],
  1305. ['loveItems' => ['$elemMatch' => ['sellable.$id' => $referencedId]]]
  1306. );
  1307. $this->assertArrayHasKey('loveItems', $item);
  1308. $this->assertCount(1, $item['loveItems']);
  1309. $cursor = $collection->find(
  1310. ['_id' => $id],
  1311. ['loveItems' => ['$elemMatch' => ['sellable.$id' => $referencedId]]]
  1312. );
  1313. $items = iterator_to_array($cursor, false);
  1314. $this->assertCount(1, $items);
  1315. $this->assertCount(1, $items[0]['loveItems']);
  1316. }
  1317. }
  1318. class PrivatePropertiesStub
  1319. {
  1320. private $foo = 'bar';
  1321. }