MongoCollectionTest.php 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  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->assertEquals($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->assertEquals(
  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->assertEquals($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->assertEquals($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->assertEquals($expected, $result);
  312. $this->assertSame(3, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'foo']));
  313. }
  314. public function testUpdateWhichDoesntMatchQuery()
  315. {
  316. $document = ['foo' => 'bar'];
  317. $this->getCollection()->insert($document);
  318. $expected = [
  319. 'ok' => 1.0,
  320. 'nModified' => 0,
  321. 'n' => 0,
  322. 'err' => null,
  323. 'errmsg' => null,
  324. 'updatedExisting' => false,
  325. ];
  326. $result = $this->getCollection()->update(['foo' => 'bar22'], ['$set' => ['foo' => 'foo']]);
  327. $this->assertEquals($expected, $result);
  328. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'bar']));
  329. }
  330. public function testUnacknowledgedUpdate()
  331. {
  332. $document = ['foo' => 'bar'];
  333. $this->getCollection()->insert($document);
  334. unset($document['_id']);
  335. $this->getCollection()->insert($document);
  336. $this->assertTrue($this->getCollection()->update($document, ['$set' => ['foo' => 'foo']], ['w' => 0]));
  337. }
  338. public function testRemoveMultiple()
  339. {
  340. $document = ['change' => true, 'foo' => 'bar'];
  341. $this->getCollection()->insert($document);
  342. unset($document['_id']);
  343. $this->getCollection()->insert($document);
  344. $document = ['change' => true, 'foo' => 'foo'];
  345. $this->getCollection()->insert($document);
  346. $expected = [
  347. 'ok' => 1.0,
  348. 'n' => 2,
  349. 'err' => null,
  350. 'errmsg' => null,
  351. ];
  352. $result = $this->getCollection()->remove(['foo' => 'bar']);
  353. $this->assertEquals($expected, $result);
  354. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count());
  355. }
  356. public function testRemoveSingle()
  357. {
  358. $document = ['change' => true, 'foo' => 'bar'];
  359. $this->getCollection()->insert($document);
  360. unset($document['_id']);
  361. $this->getCollection()->insert($document);
  362. unset($document['_id']);
  363. $this->getCollection()->insert($document);
  364. $expected = [
  365. 'ok' => 1.0,
  366. 'n' => 1,
  367. 'err' => null,
  368. 'errmsg' => null,
  369. ];
  370. $result = $this->getCollection()->remove(['foo' => 'bar'], ['justOne' => true]);
  371. $this->assertEquals($expected, $result);
  372. $this->assertSame(2, $this->getCheckDatabase()->selectCollection('test')->count());
  373. }
  374. public function testRemoveUnacknowledged()
  375. {
  376. $document = ['change' => true, 'foo' => 'bar'];
  377. $this->getCollection()->insert($document);
  378. unset($document['_id']);
  379. $this->getCollection()->insert($document);
  380. unset($document['_id']);
  381. $this->getCollection()->insert($document);
  382. $this->assertTrue($this->getCollection()->remove(['foo' => 'bar'], ['w' => 0]));
  383. }
  384. public function testFindReturnsCursor()
  385. {
  386. $this->prepareData();
  387. $collection = $this->getCollection();
  388. $this->assertInstanceOf('MongoCursor', $collection->find());
  389. }
  390. /**
  391. * @dataProvider dataFindWithProjection
  392. */
  393. public function testFindWithProjection($projection)
  394. {
  395. $document = ['foo' => 'foo', 'bar' => 'bar'];
  396. $this->getCollection()->insert($document);
  397. unset($document['_id']);
  398. $this->getCollection()->insert($document);
  399. $cursor = $this->getCollection()->find(['foo' => 'foo'], $projection);
  400. foreach ($cursor as $document) {
  401. $this->assertCount(2, $document);
  402. $this->assertArrayHasKey('_id', $document);
  403. $this->assertArraySubset(['bar' => 'bar'], $document);
  404. }
  405. }
  406. public static function dataFindWithProjection()
  407. {
  408. return [
  409. 'projection' => [['bar' => true]],
  410. 'intProjection' => [['bar' => 1]],
  411. 'legacyProjection' => [['bar']],
  412. ];
  413. }
  414. /**
  415. * @dataProvider dataFindWithProjectionAndNumericKeys
  416. */
  417. public function testFindWithProjectionAndNumericKeys($data, $projection, $expected)
  418. {
  419. $this->getCollection()->insert($data);
  420. $document = $this->getCollection()->findOne([], $projection);
  421. unset($document['_id']);
  422. $this->assertSame($expected, $document);
  423. }
  424. public static function dataFindWithProjectionAndNumericKeys()
  425. {
  426. return [
  427. 'sequentialIntegersStartingWithOne' => [
  428. ['0' => 'foo', '1' => 'bar', '2' => 'foobar'],
  429. [1 => true, 2 => true],
  430. ['1' => 'bar', '2' => 'foobar'],
  431. ],
  432. 'nonSequentialIntegers' => [
  433. ['0' => 'foo', '1' => 'bar', '2' => 'foobar', '3' => 'barfoo'],
  434. [1 => true, 3 => true],
  435. ['1' => 'bar', '3' => 'barfoo'],
  436. ]
  437. ];
  438. }
  439. public function testFindWithProjectionAndSequentialNumericKeys()
  440. {
  441. $this->expectException(\MongoException::class);
  442. $this->expectExceptionMessage('field names must be strings', 8);
  443. $this->getCollection()->findOne([], [true, false]);
  444. }
  445. /**
  446. * @dataProvider dataFindWithProjectionExcludeId
  447. */
  448. public function testFindWithProjectionExcludeId($projection)
  449. {
  450. $document = ['foo' => 'foo', 'bar' => 'bar'];
  451. $this->getCollection()->insert($document);
  452. unset($document['_id']);
  453. $this->getCollection()->insert($document);
  454. $cursor = $this->getCollection()->find(['foo' => 'foo'], $projection);
  455. foreach ($cursor as $document) {
  456. $this->assertCount(1, $document);
  457. $this->assertArrayNotHasKey('_id', $document);
  458. $this->assertArraySubset(['bar' => 'bar'], $document);
  459. }
  460. }
  461. public static function dataFindWithProjectionExcludeId()
  462. {
  463. return [
  464. 'projection' => [['_id' => false, 'bar' => true]],
  465. 'intProjection' => [['_id' => 0, 'bar' => 1]],
  466. ];
  467. }
  468. public function testCount()
  469. {
  470. $this->prepareData();
  471. $collection = $this->getCollection();
  472. $this->assertSame(3, $collection->count());
  473. $this->assertSame(2, $collection->count(['foo' => 'bar']));
  474. }
  475. public function testCountWithLimit()
  476. {
  477. $this->prepareData();
  478. $collection = $this->getCollection();
  479. $this->assertSame(2, $collection->count([], ['limit' => 2]));
  480. $this->assertSame(1, $collection->count(['foo' => 'bar'], ['limit' => 1]));
  481. }
  482. public function testCountWithLimitLegacy()
  483. {
  484. $this->prepareData();
  485. $collection = $this->getCollection();
  486. $this->assertSame(2, $collection->count([], 2));
  487. $this->assertSame(1, $collection->count(['foo' => 'bar'], 1));
  488. }
  489. public function testCountWithSkip()
  490. {
  491. $this->prepareData();
  492. $collection = $this->getCollection();
  493. $this->assertSame(2, $collection->count([], ['skip' => 1]));
  494. $this->assertSame(1, $collection->count(['foo' => 'bar'], ['skip' => 1]));
  495. }
  496. public function testCountWithSkipLegacy()
  497. {
  498. $this->prepareData();
  499. $collection = $this->getCollection();
  500. $this->assertSame(2, $collection->count([], null, 1));
  501. $this->assertSame(1, $collection->count(['foo' => 'bar'], null, 1));
  502. }
  503. public function testCountWithLimitAndSkip()
  504. {
  505. $this->prepareData();
  506. $collection = $this->getCollection();
  507. $this->assertSame(2, $collection->count([], ['skip' => 1, 'limit' => 2]));
  508. $this->assertSame(1, $collection->count([], ['skip' => 1, 'limit' => 1]));
  509. }
  510. public function testCountWithLimitAndSkipLegacy()
  511. {
  512. $this->prepareData();
  513. $collection = $this->getCollection();
  514. $this->assertSame(2, $collection->count([], 2, 1));
  515. $this->assertSame(1, $collection->count([], 1, 1));
  516. }
  517. public function testCountTimeout()
  518. {
  519. $this->failMaxTimeMS();
  520. $this->expectException(\MongoExecutionTimeoutException::class);
  521. $this->getCollection()->count([], ['maxTimeMS' => 1]);
  522. }
  523. public function testFindOne()
  524. {
  525. $this->prepareData();
  526. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
  527. $this->assertSame(['foo' => 'foo'], $document);
  528. }
  529. public function testFindOneWithProjection()
  530. {
  531. $document = ['foo' => 'foo', 'bar' => 'bar'];
  532. $this->getCollection()->insert($document);
  533. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['bar' => true]);
  534. $this->assertCount(2, $document);
  535. $this->assertArraySubset(['bar' => 'bar'], $document);
  536. }
  537. public function testFindOneWithLegacyProjection()
  538. {
  539. $document = ['foo' => 'foo', 'bar' => 'bar'];
  540. $this->getCollection()->insert($document);
  541. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['bar']);
  542. $this->assertCount(2, $document);
  543. $this->assertArraySubset(['bar' => 'bar'], $document);
  544. }
  545. public function testFindOneNotFound()
  546. {
  547. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
  548. $this->assertNull($document);
  549. }
  550. public function testFindOneConnectionIssue()
  551. {
  552. $this->expectException(\MongoConnectionException::class);
  553. $client = $this->getClient([], 'mongodb://localhost:28888/?connectTimeoutMS=1');
  554. $collection = $client->selectCollection('mongo-php-adapter', 'test');
  555. $collection->findOne();
  556. }
  557. public function testDistinct()
  558. {
  559. $this->prepareData();
  560. $values = $this->getCollection()->distinct('foo');
  561. $this->assertInternalType('array', $values);
  562. sort($values);
  563. $this->assertEquals(['bar', 'foo'], $values);
  564. }
  565. public function testDistinctWithQuery()
  566. {
  567. $this->prepareData();
  568. $values = $this->getCollection()->distinct('foo', ['foo' => 'bar']);
  569. $this->assertInternalType('array', $values);
  570. $this->assertEquals(['bar'], $values);
  571. }
  572. public function testDistinctWithIdQuery()
  573. {
  574. $document1 = ['foo' => 'bar'];
  575. $document2 = ['foo' => 'bar'];
  576. $document3 = ['foo' => 'foo'];
  577. $collection = $this->getCollection();
  578. $collection->insert($document1);
  579. $collection->insert($document2);
  580. $collection->insert($document3);
  581. $this->assertSame(
  582. ['bar'],
  583. $collection->distinct('foo', ['_id' => [
  584. '$in' => [$document1['_id'], $document2['_id']]
  585. ]])
  586. );
  587. $this->assertEquals(
  588. ['bar', 'foo'],
  589. $collection->distinct('foo', ['_id' => [
  590. '$in' => [$document1['_id'], $document3['_id']]
  591. ]])
  592. );
  593. }
  594. public function testAggregate()
  595. {
  596. $collection = $this->getCollection();
  597. $this->prepareData();
  598. $pipeline = [
  599. [
  600. '$group' => [
  601. '_id' => '$foo',
  602. 'count' => [ '$sum' => 1 ],
  603. ],
  604. ],
  605. [
  606. '$sort' => ['_id' => 1]
  607. ]
  608. ];
  609. $result = $collection->aggregate($pipeline);
  610. $this->assertInternalType('array', $result);
  611. $this->assertArrayHasKey('result', $result);
  612. $this->assertEquals([
  613. ['_id' => 'bar', 'count' => 2],
  614. ['_id' => 'foo', 'count' => 1],
  615. ], $result['result']);
  616. }
  617. public function testAggregateWithMultiplePilelineOperatorsAsArguments()
  618. {
  619. $collection = $this->getCollection();
  620. $this->prepareData();
  621. try {
  622. $result = $collection->aggregate(
  623. [
  624. '$group' => [
  625. '_id' => '$foo',
  626. 'count' => [ '$sum' => 1 ],
  627. ],
  628. ],
  629. [
  630. '$sort' => ['_id' => 1]
  631. ]
  632. );
  633. } catch (\MongoResultException $ex) {
  634. $msg = 'MongoCollection::aggregate ( array $op [, array $op [, array $... ]] ) should accept variable amount of pipeline operators as argument'
  635. . "\n"
  636. . $ex;
  637. $this->fail($msg);
  638. }
  639. $this->assertInternalType('array', $result);
  640. $this->assertArrayHasKey('result', $result);
  641. $this->assertEquals([
  642. ['_id' => 'bar', 'count' => 2],
  643. ['_id' => 'foo', 'count' => 1],
  644. ], $result['result']);
  645. }
  646. public function testAggregateInvalidPipeline()
  647. {
  648. $collection = $this->getCollection();
  649. $pipeline = [
  650. [
  651. '$invalid' => []
  652. ],
  653. ];
  654. $this->expectException(\MongoResultException::class);
  655. $this->expectExceptionMessage('Unrecognized pipeline stage name');
  656. $collection->aggregate($pipeline);
  657. }
  658. public function testAggregateTimeoutException()
  659. {
  660. $collection = $this->getCollection();
  661. $this->failMaxTimeMS();
  662. $this->expectException(\MongoExecutionTimeoutException::class);
  663. $pipeline = [
  664. [
  665. '$group' => [
  666. '_id' => '$foo',
  667. 'count' => [ '$sum' => 1 ],
  668. ],
  669. ],
  670. [
  671. '$sort' => ['_id' => 1]
  672. ]
  673. ];
  674. $collection->aggregate($pipeline, ['maxTimeMS' => 1]);
  675. }
  676. public function testAggregateCursor()
  677. {
  678. $collection = $this->getCollection();
  679. $this->prepareData();
  680. $pipeline = [
  681. [
  682. '$group' => [
  683. '_id' => '$foo',
  684. 'count' => [ '$sum' => 1 ],
  685. ],
  686. ],
  687. [
  688. '$sort' => ['_id' => 1]
  689. ]
  690. ];
  691. $cursor = $collection->aggregateCursor($pipeline);
  692. $this->assertInstanceOf('MongoCommandCursor', $cursor);
  693. $this->assertEquals([
  694. ['_id' => 'bar', 'count' => 2],
  695. ['_id' => 'foo', 'count' => 1],
  696. ], iterator_to_array($cursor));
  697. }
  698. public function testReadPreference()
  699. {
  700. $collection = $this->getCollection();
  701. $this->assertSame(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  702. $this->assertFalse($collection->getSlaveOkay());
  703. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  704. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  705. $this->assertTrue($collection->getSlaveOkay());
  706. $this->assertTrue($collection->setSlaveOkay(true));
  707. $this->assertSame(['type' => \MongoClient::RP_SECONDARY_PREFERRED, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  708. $this->assertTrue($collection->setSlaveOkay(false));
  709. $this->assertArraySubset(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  710. }
  711. public function testReadPreferenceIsSetInDriver()
  712. {
  713. $this->skipTestIf(extension_loaded('mongo'));
  714. $collection = $this->getCollection();
  715. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  716. // Only way to check whether options are passed down is through debugInfo
  717. $readPreference = $collection->getCollection()->__debugInfo()['readPreference'];
  718. $this->assertSame(ReadPreference::RP_SECONDARY, $readPreference->getMode());
  719. $this->assertSame([['a' => 'b']], $readPreference->getTagSets());
  720. }
  721. public function testReadPreferenceIsInherited()
  722. {
  723. $database = $this->getDatabase();
  724. $database->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]);
  725. $collection = $database->selectCollection('test');
  726. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  727. }
  728. public function testWriteConcern()
  729. {
  730. $collection = $this->getCollection();
  731. $this->assertTrue($collection->setWriteConcern('majority', 100));
  732. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  733. }
  734. public function testWriteConcernIsSetInDriver()
  735. {
  736. $this->skipTestIf(extension_loaded('mongo'));
  737. $collection = $this->getCollection();
  738. $this->assertTrue($collection->setWriteConcern(2, 100));
  739. // Only way to check whether options are passed down is through debugInfo
  740. $writeConcern = $collection->getCollection()->__debugInfo()['writeConcern'];
  741. $this->assertSame(2, $writeConcern->getW());
  742. $this->assertSame(100, $writeConcern->getWtimeout());
  743. }
  744. public function testWriteConcernIsInherited()
  745. {
  746. $database = $this->getDatabase();
  747. $database->setWriteConcern('majority', 100);
  748. $collection = $database->selectCollection('test');
  749. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  750. }
  751. public function testSaveInsert()
  752. {
  753. $id = '54203e08d51d4a1f868b456e';
  754. $collection = $this->getCollection();
  755. $objectId = new \MongoId($id);
  756. $expected = [
  757. 'ok' => 1.0,
  758. 'nModified' => 0,
  759. 'n' => 1,
  760. 'err' => null,
  761. 'errmsg' => null,
  762. 'upserted' => $objectId,
  763. 'updatedExisting' => false,
  764. ];
  765. $document = ['_id' => $objectId, 'foo' => 'bar'];
  766. $this->assertEquals($expected, $collection->save($document));
  767. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  768. $this->assertSame(1, $newCollection->count());
  769. $object = $newCollection->findOne();
  770. $this->assertNotNull($object);
  771. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  772. $this->assertSame($id, (string) $object->_id);
  773. $this->assertObjectHasAttribute('foo', $object);
  774. $this->assertAttributeSame('bar', 'foo', $object);
  775. }
  776. public function testRemoveOne()
  777. {
  778. $id = '54203e08d51d4a1f868b456e';
  779. $collection = $this->getCollection();
  780. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  781. $collection->insert($document);
  782. $collection->remove(['_id' => new \MongoId($id)]);
  783. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  784. $this->assertSame(0, $newCollection->count());
  785. }
  786. public function testSaveUpdate()
  787. {
  788. $expected = [
  789. 'ok' => 1.0,
  790. 'nModified' => 1,
  791. 'n' => 1,
  792. 'err' => null,
  793. 'errmsg' => null,
  794. 'updatedExisting' => true,
  795. ];
  796. $id = '54203e08d51d4a1f868b456e';
  797. $collection = $this->getCollection();
  798. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  799. $saveDocument = ['_id' => new \MongoId($id), 'foo' => 'foo'];
  800. $collection->insert($insertDocument);
  801. $this->assertEquals($expected, $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->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  807. $this->assertSame($id, (string) $object->_id);
  808. $this->assertObjectHasAttribute('foo', $object);
  809. $this->assertAttributeSame('foo', 'foo', $object);
  810. }
  811. public function testSavingShouldReplaceTheWholeDocument() {
  812. $id = '54203e08d51d4a1f868b456e';
  813. $collection = $this->getCollection();
  814. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  815. $saveDocument = ['_id' => new \MongoId($id)];
  816. $collection->insert($insertDocument);
  817. $collection->save($saveDocument);
  818. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  819. $this->assertSame(1, $newCollection->count());
  820. $object = $newCollection->findOne();
  821. $this->assertNotNull($object);
  822. $this->assertObjectNotHasAttribute('foo', $object);
  823. }
  824. public function testSaveDuplicate()
  825. {
  826. $collection = $this->getCollection();
  827. $collection->createIndex(['foo' => 1], ['unique' => true]);
  828. $document = ['foo' => 'bar'];
  829. $collection->save($document);
  830. $this->expectException(\MongoDuplicateKeyException::class);
  831. unset($document['_id']);
  832. $collection->save($document);
  833. }
  834. public function testSaveEmptyKeys()
  835. {
  836. $document = [];
  837. $this->getCollection()->save($document);
  838. $this->assertSame(1, $this->getCollection()->count());
  839. }
  840. public function testSaveEmptyObject()
  841. {
  842. $document = (object) [];
  843. $this->getCollection()->save($document);
  844. $this->assertSame(1, $this->getCollection()->count());
  845. }
  846. public function testGetDBRef()
  847. {
  848. $collection = $this->getCollection();
  849. $insertDocument = ['_id' => 1, 'foo' => 'bar'];
  850. $collection->insert($insertDocument);
  851. $document = $collection->getDBRef([
  852. '$ref' => 'test',
  853. '$id' => 1,
  854. ]);
  855. $this->assertEquals($insertDocument, $document);
  856. }
  857. public function testCreateDBRef()
  858. {
  859. $collection = $this->getCollection();
  860. $reference = $collection->createDBRef(['_id' => 'foo']);
  861. $this->assertSame(
  862. [
  863. '$ref' => 'test',
  864. '$id' => 'foo',
  865. ],
  866. $reference
  867. );
  868. }
  869. public function testCreateIndex()
  870. {
  871. $expected = [
  872. 'createdCollectionAutomatically' => true,
  873. 'numIndexesBefore' => 1,
  874. 'numIndexesAfter' => 2,
  875. 'ok' => 1.0,
  876. ];
  877. $collection = $this->getCollection();
  878. $this->assertSame($expected, $collection->createIndex(['foo' => 1]));
  879. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  880. $iterator = $newCollection->listIndexes();
  881. $indexes = iterator_to_array($iterator);
  882. $this->assertCount(2, $indexes);
  883. $index = $indexes[1];
  884. $this->assertSame(['foo' => 1], $index->getKey());
  885. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  886. }
  887. public function testCreateIndexInvalid()
  888. {
  889. $this->expectException(\MongoException::class);
  890. $this->expectExceptionMessage('index specification has no elements');
  891. $this->getCollection()->createIndex([]);
  892. }
  893. public function testCreateIndexTwice()
  894. {
  895. $this->getCollection()->createIndex(['foo' => 1]);
  896. $expected = [
  897. 'createdCollectionAutomatically' => false,
  898. 'numIndexesBefore' => 2,
  899. 'numIndexesAfter' => 2,
  900. 'note' => 'all indexes already exist',
  901. 'ok' => 1.0
  902. ];
  903. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  904. }
  905. public function testCreateIndexWithDeprecatedOptions()
  906. {
  907. $this->getCollection()->createIndex(['foo' => 1], ['w' => 1]);
  908. $expected = [
  909. 'createdCollectionAutomatically' => false,
  910. 'numIndexesBefore' => 2,
  911. 'numIndexesAfter' => 2,
  912. 'note' => 'all indexes already exist',
  913. 'ok' => 1.0
  914. ];
  915. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  916. }
  917. public function testCreateIndexTwiceWithSameName()
  918. {
  919. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  920. $expected = [
  921. 'createdCollectionAutomatically' => false,
  922. 'numIndexesBefore' => 2,
  923. 'numIndexesAfter' => 2,
  924. 'note' => 'all indexes already exist',
  925. 'ok' => 1.0
  926. ];
  927. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']));
  928. }
  929. public function testCreateIndexTwiceWithDifferentName()
  930. {
  931. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  932. $expected = [
  933. 'createdCollectionAutomatically' => false,
  934. 'numIndexesBefore' => 2,
  935. 'numIndexesAfter' => 2,
  936. 'note' => 'all indexes already exist',
  937. 'ok' => 1.0
  938. ];
  939. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'index_test']));
  940. }
  941. public function testCreateIndexTwiceWithDifferentOrder()
  942. {
  943. $this->getCollection()->createIndex(['foo' => 1, 'bar' => 1]);
  944. $expected = [
  945. 'createdCollectionAutomatically' => false,
  946. 'numIndexesBefore' => 2,
  947. 'numIndexesAfter' => 3,
  948. 'ok' => 1.0
  949. ];
  950. $this->assertSame($expected, $this->getCollection()->createIndex(['bar' => 1, 'foo' => 1]));
  951. }
  952. public function testCreateIndexesWithDifferentOptions()
  953. {
  954. $this->expectException(\MongoResultException::class);
  955. $this->getCollection()->createIndex(['foo' => 1]);
  956. $this->getCollection()->createIndex(['foo' => 1], ['unique' => true]);
  957. }
  958. /**
  959. * @dataProvider createIndexIgnoredOptions
  960. */
  961. public function testCreateIndexesWithIgnoredOptions($option)
  962. {
  963. $this->getCollection()->createIndex(['foo' => 1]);
  964. $expected = [
  965. 'createdCollectionAutomatically' => false,
  966. 'numIndexesBefore' => 2,
  967. 'numIndexesAfter' => 2,
  968. 'note' => 'all indexes already exist',
  969. 'ok' => 1.0
  970. ];
  971. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], [$option => true]));
  972. }
  973. public static function createIndexIgnoredOptions()
  974. {
  975. return [
  976. 'background' => ['background'],
  977. 'dropDups' => ['dropDups'],
  978. ];
  979. }
  980. public function testCreateIndexWithSameNameAndDifferentOptions()
  981. {
  982. $this->expectException(\MongoResultException::class);
  983. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'foo']);
  984. $this->getCollection()->createIndex(['bar' => 1], ['name' => 'foo']);
  985. }
  986. public function testEnsureIndex()
  987. {
  988. $expected = [
  989. 'createdCollectionAutomatically' => true,
  990. 'numIndexesBefore' => 1,
  991. 'numIndexesAfter' => 2,
  992. 'ok' => 1.0
  993. ];
  994. $collection = $this->getCollection();
  995. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  996. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  997. $indexes = iterator_to_array($newCollection->listIndexes());
  998. $this->assertCount(2, $indexes);
  999. $index = $indexes[1];
  1000. $this->assertSame(['bar' => 1], $index->getKey());
  1001. $this->assertTrue($index->isUnique());
  1002. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  1003. }
  1004. public function testEnsureIndexAlreadyExists()
  1005. {
  1006. $collection = $this->getCollection();
  1007. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  1008. $expected = [
  1009. 'createdCollectionAutomatically' => false,
  1010. 'numIndexesBefore' => 2,
  1011. 'numIndexesAfter' => 2,
  1012. 'ok' => 1.0,
  1013. 'note' => 'all indexes already exist',
  1014. ];
  1015. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  1016. }
  1017. public function testEnsureIndexAlreadyExistsWithDifferentOptions()
  1018. {
  1019. $collection = $this->getCollection();
  1020. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  1021. $this->expectException(\MongoResultException::class);
  1022. $this->expectExceptionMessage('Index with name: bar_1 already exists with different options');
  1023. $collection->ensureIndex(['bar' => 1]);
  1024. }
  1025. public function testDeleteIndexUsingIndexName()
  1026. {
  1027. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1028. $newCollection->createIndex(['bar' => 1], ['name' => 'bar']);
  1029. $expected = [
  1030. 'nIndexesWas' => 2,
  1031. 'errmsg' => 'index not found with name [bar_1]',
  1032. 'ok' => 0.0,
  1033. ];
  1034. if (version_compare($this->getServerVersion(), '3.4.0', '>=')) {
  1035. $expected['code'] = 27;
  1036. }
  1037. // Using assertArraySubset because newer versions (3.4.7?) also return `codeName`
  1038. $this->assertArraySubset($expected, $this->getCollection()->deleteIndex('bar'));
  1039. $this->assertCount(2, iterator_to_array($newCollection->listIndexes()));
  1040. }
  1041. public function testDeleteIndexUsingField()
  1042. {
  1043. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1044. $newCollection->createIndex(['bar' => 1]);
  1045. $expected = [
  1046. 'nIndexesWas' => 2,
  1047. 'ok' => 1.0,
  1048. ];
  1049. $this->assertSame($expected, $this->getCollection()->deleteIndex('bar'));
  1050. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  1051. }
  1052. public function testDeleteIndexUsingKeys()
  1053. {
  1054. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1055. $newCollection->createIndex(['bar' => 1]);
  1056. $expected = [
  1057. 'nIndexesWas' => 2,
  1058. 'ok' => 1.0,
  1059. ];
  1060. $this->assertSame($expected, $this->getcollection()->deleteIndex(['bar' => 1]));
  1061. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  1062. }
  1063. public function testDeleteIndexes()
  1064. {
  1065. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1066. $newCollection->createIndex(['bar' => 1]);
  1067. $expected = [
  1068. 'nIndexesWas' => 2,
  1069. 'msg' => 'non-_id indexes dropped for collection',
  1070. 'ok' => 1.0,
  1071. ];
  1072. $this->assertSame($expected, $this->getcollection()->deleteIndexes());
  1073. $this->assertCount(1, iterator_to_array($newCollection->listIndexes())); // ID index is present by default
  1074. }
  1075. public function testDeleteIndexesForNonExistingCollection()
  1076. {
  1077. $expected = [
  1078. 'ok' => 0.0,
  1079. 'errmsg' => 'ns not found',
  1080. ];
  1081. if (version_compare($this->getServerVersion(), '3.4.0', '>=')) {
  1082. $expected['code'] = 26;
  1083. }
  1084. // Using assertArraySubset because newer versions (3.4.7?) also return `codeName`
  1085. $this->assertArraySubset($expected, $this->getCollection('nonExisting')->deleteIndexes());
  1086. }
  1087. public function dataGetIndexInfo()
  1088. {
  1089. $indexVersion = $this->getDefaultIndexVersion();
  1090. return [
  1091. 'plainIndex' => [
  1092. 'expectedIndex' => [
  1093. 'v' => $indexVersion,
  1094. 'key' => ['foo' => 1],
  1095. 'name' => 'foo_1',
  1096. 'ns' => 'mongo-php-adapter.test',
  1097. ],
  1098. 'fields' => ['foo' => 1],
  1099. 'options' => [],
  1100. ],
  1101. 'uniqueIndex' => [
  1102. 'expectedIndex' => [
  1103. 'v' => $indexVersion,
  1104. 'key' => ['foo' => 1],
  1105. 'name' => 'foo_1',
  1106. 'ns' => 'mongo-php-adapter.test',
  1107. 'unique' => true,
  1108. ],
  1109. 'fields' => ['foo' => 1],
  1110. 'options' => ['unique' => true],
  1111. ],
  1112. 'sparseIndex' => [
  1113. 'expectedIndex' => [
  1114. 'v' => $indexVersion,
  1115. 'key' => ['foo' => 1],
  1116. 'name' => 'foo_1',
  1117. 'ns' => 'mongo-php-adapter.test',
  1118. 'sparse' => true,
  1119. ],
  1120. 'fields' => ['foo' => 1],
  1121. 'options' => ['sparse' => true],
  1122. ],
  1123. 'ttlIndex' => [
  1124. 'expectedIndex' => [
  1125. 'v' => $indexVersion,
  1126. 'key' => ['foo' => 1],
  1127. 'name' => 'foo_1',
  1128. 'ns' => 'mongo-php-adapter.test',
  1129. 'expireAfterSeconds' => 86400,
  1130. ],
  1131. 'fields' => ['foo' => 1],
  1132. 'options' => ['expireAfterSeconds' => 86400],
  1133. ],
  1134. 'textIndex' => [
  1135. 'expectedIndex' => [
  1136. 'v' => $indexVersion,
  1137. 'key' => [
  1138. '_fts' => 'text',
  1139. '_ftsx' => 1,
  1140. ],
  1141. 'name' => 'foo_text',
  1142. 'ns' => 'mongo-php-adapter.test',
  1143. 'weights' => [
  1144. 'foo' => 1,
  1145. ],
  1146. 'default_language' => 'english',
  1147. 'language_override' => 'language',
  1148. 'textIndexVersion' => version_compare($this->getServerVersion(), '3.2.0', '>=') ? 3 : 2,
  1149. ],
  1150. 'fields' => ['foo' => 'text'],
  1151. 'options' => [],
  1152. ],
  1153. 'partialFilterExpression' => [
  1154. 'expectedIndex' => [
  1155. 'v' => $indexVersion,
  1156. 'key' => ['foo' => 1],
  1157. 'name' => 'foo_1',
  1158. 'ns' => 'mongo-php-adapter.test',
  1159. 'partialFilterExpression' => [
  1160. 'bar' => ['$gt' => 1],
  1161. ],
  1162. ],
  1163. 'fields' => ['foo' => 1],
  1164. 'options' => [
  1165. 'partialFilterExpression' => ['bar' => ['$gt' => 1]],
  1166. ],
  1167. ],
  1168. 'geoSpatial' => [
  1169. 'expectedIndex' => [
  1170. 'v' => $indexVersion,
  1171. 'key' => ['foo' => '2dsphere'],
  1172. 'name' => 'foo_2dsphere',
  1173. 'ns' => 'mongo-php-adapter.test',
  1174. '2dsphereIndexVersion' => version_compare($this->getServerVersion(), '3.2.0', '>=') ? 3 : 2,
  1175. ],
  1176. 'fields' => ['foo' => '2dsphere'],
  1177. 'options' => [],
  1178. ],
  1179. 'geoHaystack' => [
  1180. 'expectedIndex' => [
  1181. 'v' => $indexVersion,
  1182. 'key' => ['foo' => 'geoHaystack', 'bar' => 1],
  1183. 'name' => 'foo_geoHaystack_bar_1',
  1184. 'ns' => 'mongo-php-adapter.test',
  1185. 'bucketSize' => 10,
  1186. ],
  1187. 'fields' => ['foo' => 'geoHaystack', 'bar' => 1],
  1188. 'options' => ['bucketSize' => 10],
  1189. ],
  1190. ];
  1191. }
  1192. /**
  1193. * @dataProvider dataGetIndexInfo
  1194. */
  1195. public function testGetIndexInfo($expectedIndex, $fields, $options)
  1196. {
  1197. $idIndex = [
  1198. 'v' => $this->getDefaultIndexVersion(),
  1199. 'key' => ['_id' => 1],
  1200. 'name' => '_id_',
  1201. 'ns' => 'mongo-php-adapter.test',
  1202. ];
  1203. $expectedIndexInfo = [$idIndex, $expectedIndex];
  1204. $collection = $this->getCollection();
  1205. $collection->createIndex($fields, $options);
  1206. $this->assertEquals(
  1207. $expectedIndexInfo,
  1208. $collection->getIndexInfo()
  1209. );
  1210. }
  1211. public function testFindAndModifyUpdate()
  1212. {
  1213. $id = '54203e08d51d4a1f868b456e';
  1214. $collection = $this->getCollection();
  1215. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1216. $collection->insert($document);
  1217. $document = $collection->findAndModify(
  1218. ['_id' => new \MongoId($id)],
  1219. ['$set' => ['foo' => 'foo']]
  1220. );
  1221. $this->assertSame('bar', $document['foo']);
  1222. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1223. $this->assertSame(1, $newCollection->count());
  1224. $object = $newCollection->findOne();
  1225. $this->assertNotNull($object);
  1226. $this->assertAttributeSame('foo', 'foo', $object);
  1227. }
  1228. public function testFindAndModifyUpdateWithUpdateOptions()
  1229. {
  1230. $id = '54203e08d51d4a1f868b456e';
  1231. $collection = $this->getCollection();
  1232. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1233. $collection->insert($document);
  1234. $document = $collection->findAndModify(
  1235. ['_id' => new \MongoId($id)],
  1236. [],
  1237. [],
  1238. [
  1239. 'update' => ['bar' => 'foo']
  1240. ]
  1241. );
  1242. $this->assertSame('bar', $document['foo']);
  1243. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1244. $this->assertSame(1, $newCollection->count());
  1245. $object = $newCollection->findOne();
  1246. $this->assertNotNull($object);
  1247. $this->assertAttributeSame('foo', 'bar', $object);
  1248. $this->assertObjectNotHasAttribute('foo', $object);
  1249. }
  1250. public function testFindAndModifyWithUpdateParamAndOption()
  1251. {
  1252. $id = '54203e08d51d4a1f868b456e';
  1253. $collection = $this->getCollection();
  1254. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1255. $collection->insert($document);
  1256. $data = ['foo' => 'foo', 'bar' => 'bar'];
  1257. $this->getCollection()->findAndModify(
  1258. ['_id' => new \MongoId($id)],
  1259. [$data],
  1260. [],
  1261. [
  1262. 'update' => ['$set' => ['foo' => 'foobar']],
  1263. 'upsert' => true,
  1264. ]
  1265. );
  1266. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1267. $this->assertSame(1, $newCollection->count());
  1268. $object = $newCollection->findOne();
  1269. $this->assertNotNull($object);
  1270. $this->assertAttributeSame('foobar', 'foo', $object);
  1271. $this->assertObjectNotHasAttribute('bar', $object);
  1272. }
  1273. public function testFindAndModifyUpdateReplace()
  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. ['_id' => new \MongoId($id), 'foo' => 'boo']
  1282. );
  1283. $this->assertSame('bar', $document['foo']);
  1284. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1285. $this->assertSame(1, $newCollection->count());
  1286. $object = $newCollection->findOne();
  1287. $this->assertNotNull($object);
  1288. $this->assertAttributeSame('boo', 'foo', $object);
  1289. $this->assertObjectNotHasAttribute('bar', $object);
  1290. }
  1291. public function testFindAndModifyUpdateReturnNew()
  1292. {
  1293. $id = '54203e08d51d4a1f868b456e';
  1294. $collection = $this->getCollection();
  1295. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1296. $collection->insert($document);
  1297. $document = $collection->findAndModify(
  1298. ['_id' => new \MongoId($id)],
  1299. ['$set' => ['foo' => 'foo']],
  1300. null,
  1301. ['new' => true]
  1302. );
  1303. $this->assertSame('foo', $document['foo']);
  1304. }
  1305. public function testFindAndModifyWithFields()
  1306. {
  1307. $id = '54203e08d51d4a1f868b456e';
  1308. $collection = $this->getCollection();
  1309. $document = [
  1310. '_id' => new \MongoId($id),
  1311. 'foo' => 'bar',
  1312. 'bar' => 'foo',
  1313. ];
  1314. $collection->insert($document);
  1315. $document = $collection->findAndModify(
  1316. ['_id' => new \MongoId($id)],
  1317. ['$set' => ['foo' => 'foo']],
  1318. ['foo' => true]
  1319. );
  1320. $this->assertArrayNotHasKey('bar', $document);
  1321. $this->assertArrayHasKey('foo', $document);
  1322. }
  1323. public function testGroup()
  1324. {
  1325. $collection = $this->getCollection();
  1326. $document1 = ['a' => 2];
  1327. $collection->insert($document1);
  1328. $document2 = ['b' => 5];
  1329. $collection->insert($document2);
  1330. $document3 = ['a' => 1];
  1331. $collection->insert($document3);
  1332. $keys = [];
  1333. $initial = ["count" => 0];
  1334. $reduce = "function (obj, prev) { prev.count++; }";
  1335. $condition = ['condition' => ["a" => [ '$gt' => 1]]];
  1336. $result = $collection->group($keys, $initial, $reduce, $condition);
  1337. $this->assertArraySubset(
  1338. [
  1339. 'retval' => [['count' => 1.0]],
  1340. 'count' => 1.0,
  1341. 'keys' => 1,
  1342. 'ok' => 1.0,
  1343. ],
  1344. $result
  1345. );
  1346. }
  1347. public function testMapReduce()
  1348. {
  1349. $data = array(
  1350. array(
  1351. 'username' => 'jones',
  1352. 'likes' => 20.0,
  1353. 'text' => 'Hello world!'
  1354. ),
  1355. array(
  1356. 'username' => 'bob',
  1357. 'likes' => 100.0,
  1358. 'text' => 'Hello world!'
  1359. ),
  1360. array(
  1361. 'username' => 'bob',
  1362. 'likes' => 100.0,
  1363. 'text' => 'Hello world!'
  1364. ),
  1365. );
  1366. $collection = $this->getCollection();
  1367. $collection->batchInsert($data);
  1368. $map = 'function() {
  1369. emit(this.username, { count: 1, likes: this.likes });
  1370. }';
  1371. $reduce = 'function(key, values) {
  1372. var result = {count: 0, likes: 0};
  1373. values.forEach(function(value) {
  1374. result.count += value.count;
  1375. result.likes += value.likes;
  1376. });
  1377. return result;
  1378. }';
  1379. $finalize = 'function (key, value) { value.test = "test"; return value; }';
  1380. $command = [
  1381. 'mapreduce' => $this->getCollection()->getName(),
  1382. 'map' => new \MongoCode($map),
  1383. 'reduce' => new \MongoCode($reduce),
  1384. 'query' => (object) [],
  1385. 'out' => ['inline' => true],
  1386. 'finalize' => new \MongoCode($finalize),
  1387. ];
  1388. $result = $this->getDatabase()->command($command);
  1389. $expected = [
  1390. [
  1391. '_id' => 'bob',
  1392. 'value' => [
  1393. 'count' => 2.0,
  1394. 'likes' => 200.0,
  1395. 'test' => 'test',
  1396. ],
  1397. ],
  1398. [
  1399. '_id' => 'jones',
  1400. 'value' => [
  1401. 'count' => 1.0,
  1402. 'likes' => 20.0,
  1403. 'test' => 'test',
  1404. ],
  1405. ],
  1406. ];
  1407. $this->assertSame(1.0, $result['ok']);
  1408. $this->assertSame($expected, $result['results']);
  1409. }
  1410. public function testFindAndModifyResultException()
  1411. {
  1412. $this->markTestSkipped('Test fails on travis-ci - skipped while investigating this');
  1413. $collection = $this->getCollection();
  1414. $this->expectException(\MongoResultException::class);
  1415. $collection->findAndModify(
  1416. array("inprogress" => false, "name" => "Next promo"),
  1417. array('$unsupportedOperator' => array("tasks" => -1)),
  1418. array("tasks" => true),
  1419. array("new" => true)
  1420. );
  1421. }
  1422. public function testFindAndModifyExceptionTimeout()
  1423. {
  1424. $this->failMaxTimeMS();
  1425. $id = '54203e08d51d4a1f868b456e';
  1426. $collection = $this->getCollection();
  1427. $this->expectException(\MongoExecutionTimeoutException::class);
  1428. $document = $collection->findAndModify(
  1429. ['_id' => new \MongoId($id)],
  1430. null,
  1431. null,
  1432. ['maxTimeMS' => 1, 'remove' => true]
  1433. );
  1434. }
  1435. public function testFindAndModifyRemove()
  1436. {
  1437. $id = '54203e08d51d4a1f868b456e';
  1438. $collection = $this->getCollection();
  1439. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1440. $collection->insert($document);
  1441. $document = $collection->findAndModify(
  1442. ['_id' => new \MongoId($id)],
  1443. null,
  1444. null,
  1445. ['remove' => true]
  1446. );
  1447. $this->assertEquals('bar', $document['foo']);
  1448. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1449. $this->assertSame(0, $newCollection->count());
  1450. }
  1451. public function testValidate()
  1452. {
  1453. $collection = $this->getCollection();
  1454. $document = ['foo' => 'bar'];
  1455. $collection->insert($document);
  1456. $result = $collection->validate();
  1457. $this->assertArraySubset(
  1458. [
  1459. 'ns' => 'mongo-php-adapter.test',
  1460. 'nrecords' => 1,
  1461. 'nIndexes' => 1,
  1462. 'keysPerIndex' => ['mongo-php-adapter.test.$_id_' => 1],
  1463. 'valid' => true,
  1464. 'errors' => [],
  1465. ],
  1466. $result
  1467. );
  1468. }
  1469. public function testDrop()
  1470. {
  1471. $document = ['foo' => 'bar'];
  1472. $this->getCollection()->insert($document);
  1473. $expected = [
  1474. 'ns' => (string) $this->getCollection(),
  1475. 'nIndexesWas' => 1,
  1476. 'ok' => 1.0
  1477. ];
  1478. $this->assertSame($expected, $this->getCollection()->drop());
  1479. }
  1480. public function testEmptyCollectionName()
  1481. {
  1482. $this->expectException(\Exception::class);
  1483. $this->expectExceptionMessage('Collection name cannot be empty');
  1484. new \MongoCollection($this->getDatabase(), '');
  1485. }
  1486. public function testSelectCollectionWithNullBytes()
  1487. {
  1488. $this->expectException(\Exception::class);
  1489. $this->expectExceptionMessage('Collection name cannot contain null bytes');
  1490. new \MongoCollection($this->getDatabase(), 'foo' . chr(0));
  1491. }
  1492. public function testSubCollectionWithNullBytes()
  1493. {
  1494. $collection = $this->getCollection();
  1495. $this->assertInstanceOf('MongoCollection', $collection->{'foo' . chr(0)});
  1496. $this->assertSame('test', $collection->getName());
  1497. }
  1498. public function testSelectCollectionWithDatabaseObject()
  1499. {
  1500. $client = $this->getClient();
  1501. $database = $this->getDatabase($client);
  1502. $collection = $client->selectCollection($database, 'test');
  1503. $this->assertSame('mongo-php-adapter.test', (string) $collection);
  1504. }
  1505. public function testHasNextLoop()
  1506. {
  1507. $collection = $this->getCollection();
  1508. for ($i = 0; $i < 5; $i++) {
  1509. $document = ['i' => $i];
  1510. $collection->insert($document);
  1511. }
  1512. $cursor = $collection->find()->sort(['i' => 1]);
  1513. $data = [];
  1514. $i = 0;
  1515. while ($cursor->hasNext()) {
  1516. $this->assertSame($i < 5, $cursor->hasNext());
  1517. $row = $cursor->getNext();
  1518. $this->assertSame($i, $row['i']);
  1519. $data[] = $row;
  1520. $i++;
  1521. }
  1522. $this->assertCount(5, $data);
  1523. }
  1524. public function testProjectionWithBSONTypes()
  1525. {
  1526. $collection = $this->getCollection();
  1527. $id = new \MongoId();
  1528. $referencedId = new \MongoId();
  1529. $data = [
  1530. '_id' => $id,
  1531. 'loveItems' => [
  1532. [
  1533. 'sellable' => [
  1534. '$ref' => 'sellables',
  1535. '$id' => $referencedId,
  1536. ]
  1537. ],
  1538. [
  1539. 'sellable' => [
  1540. '$ref' => 'sellables',
  1541. '$id' => new \MongoId(),
  1542. ]
  1543. ]
  1544. ]
  1545. ];
  1546. $collection->insert($data);
  1547. $item = $collection->findOne(
  1548. ['_id' => $id],
  1549. ['loveItems' => ['$elemMatch' => ['sellable.$id' => $referencedId]]]
  1550. );
  1551. $this->assertArrayHasKey('loveItems', $item);
  1552. $this->assertCount(1, $item['loveItems']);
  1553. $cursor = $collection->find(
  1554. ['_id' => $id],
  1555. ['loveItems' => ['$elemMatch' => ['sellable.$id' => $referencedId]]]
  1556. );
  1557. $items = iterator_to_array($cursor, false);
  1558. $this->assertCount(1, $items);
  1559. $this->assertCount(1, $items[0]['loveItems']);
  1560. }
  1561. public static function dataFindWithRegex()
  1562. {
  1563. return [
  1564. 'MongoRegex' => [new \MongoRegex('/^foo.*/i')],
  1565. 'BSONRegex' => [new Regex('^foo.*', 'i')],
  1566. ];
  1567. }
  1568. /**
  1569. * @dataProvider dataFindWithRegex
  1570. */
  1571. public function testFindWithRegex($regex)
  1572. {
  1573. $this->skipTestIf(extension_loaded('mongo'));
  1574. $document = ['name' => 'FOO 123'];
  1575. $this->getCollection()->insert($document);
  1576. $cursor = $this->getCollection()->find(['name' => $regex]);
  1577. $this->assertSame(1, $cursor->count());
  1578. }
  1579. }
  1580. class PrivatePropertiesStub
  1581. {
  1582. private $foo = 'bar';
  1583. }