example-data.txt 1.36 KB
Newer Older
1 2 3 4 5 6 7
============
Example Data
============

.. default-domain:: mongodb

Some examples in this documentation use example data fixtures from
8 9
`zips.json <https://media.mongodb.org/zips.json>`_ and
`primer-dataset.json <https://raw.githubusercontent.com/mongodb/docs-assets/primer-dataset/primer-dataset.json>`_.
10 11

Importing the dataset into MongoDB can be done in several ways. The following
12
example imports the `zips.json` file into a `test.zips` collection:
13
:php:`driver <mongodb>` directly:
14 15 16 17 18

.. code-block:: php

   <?php

19 20
   $filename = 'https://media.mongodb.org/zips.json';
   $lines = file($filename, FILE_IGNORE_NEW_LINES);
21 22 23

   $bulk = new MongoDB\Driver\BulkWrite;

24 25 26
   foreach ($lines as $line) {
       $bson = MongoDB\BSON\fromJSON($line);
       $document = MongoDB\BSON\toPHP($bson);
27 28 29 30 31
       $bulk->insert($document);
   }

   $manager = new MongoDB\Driver\Manager('mongodb://127.0.0.1/');

32
   $result = $manager->executeBulkWrite('test.zips', $bulk);
33 34 35 36 37 38
   printf("Inserted %d documents\n", $result->getInsertedCount());

The output would then resemble::

   Inserted 29353 documents

39
You may also import the datasets using :manual:`mongoimport
40 41 42 43
</reference/program/mongoimport>`, which is included with MongoDB:

.. code-block:: none

44 45
   $ mongoimport --db test --collection zips --file zips.json --drop
   $ mongoimport --db test --collection restaurants --file primer-dataset.json --drop