MongoCollectionTest.php 51 KB

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