MongoCollectionTest.php 59 KB

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