- GUI
- Windows API tutorial
- Introduction to Windows API
- Windows API main functions
- System functions in Windows API
- Strings in Windows API
- Date & time in Windows API
- A window in Windows API
- First steps in UI
- Windows API menus
- Windows API dialogs
- Windows API controls I
- Windows API controls II
- Windows API controls III
- Advanced controls in Windows API
- Custom controls in Windows API
- The GDI in Windows API
- PyQt4 tutorial
- PyQt5 tutorial
- Qt4 tutorial
- Introduction to Qt4 toolkit
- Qt4 utility classes
- Strings in Qt4
- Date and time in Qt4
- Working with files and directories in Qt4
- First programs in Qt4
- Menus and toolbars in Qt4
- Layout management in Qt4
- Events and signals in Qt4
- Qt4 Widgets
- Qt4 Widgets II
- Painting in Qt4
- Custom widget in Qt4
- The Breakout game in Qt4
- Qt5 tutorial
- Introduction to Qt5 toolkit
- Strings in Qt5
- Date and time in Qt5
- Containers in Qt5
- Working with files and directories in Qt5
- First programs in Qt5
- Menus and toolbars in Qt5
- Layout management in Qt5
- Events and signals in Qt5
- Qt5 Widgets
- Qt5 Widgets II
- Painting in Qt5
- Custom widget in Qt5
- Snake in Qt5
- The Breakout game in Qt5
- PySide tutorial
- Tkinter tutorial
- Tcl/Tk tutorial
- Qt Quick tutorial
- Java Swing tutorial
- JavaFX tutorial
- Java SWT tutorial
- wxWidgets tutorial
- Introduction to wxWidgets
- wxWidgets helper classes
- First programs in wxWidgets
- Menus and toolbars in wxWidgets
- Layout management in wxWidgets
- Events in wxWidgets
- Dialogs in wxWidgets
- wxWidgets widgets
- wxWidgets widgets II
- Drag and Drop in wxWidgets
- Device Contexts in wxWidgets
- Custom widgets in wxWidgets
- The Tetris game in wxWidgets
- wxPython tutorial
- Introduction to wxPython
- First Steps
- Menus and toolbars
- Layout management in wxPython
- Events in wxPython
- wxPython dialogs
- Widgets
- Advanced widgets in wxPython
- Drag and drop in wxPython
- Internationalisation
- Application skeletons in wxPython
- The GDI
- Mapping modes
- Creating custom widgets
- Tips and Tricks
- wxPython Gripts
- The Tetris game in wxPython
- C# Winforms Mono tutorial
- Java Gnome tutorial
- Introduction to Java Gnome
- First steps in Java Gnome
- Layout management in Java Gnome
- Layout management II in Java Gnome
- Menus in Java Gnome
- Toolbars in Java Gnome
- Events in Java Gnome
- Widgets in Java Gnome
- Widgets II in Java Gnome
- Advanced widgets in Java Gnome
- Dialogs in Java Gnome
- Pango in Java Gnome
- Drawing with Cairo in Java Gnome
- Drawing with Cairo II
- Nibbles in Java Gnome
- QtJambi tutorial
- GTK+ tutorial
- Ruby GTK tutorial
- GTK# tutorial
- Visual Basic GTK# tutorial
- PyGTK tutorial
- Introduction to PyGTK
- First steps in PyGTK
- Layout management in PyGTK
- Menus in PyGTK
- Toolbars in PyGTK
- Signals & events in PyGTK
- Widgets in PyGTK
- Widgets II in PyGTK
- Advanced widgets in PyGTK
- Dialogs in PyGTK
- Pango
- Pango II
- Drawing with Cairo in PyGTK
- Drawing with Cairo II
- Snake game in PyGTK
- Custom widget in PyGTK
- PHP GTK tutorial
- C# Qyoto tutorial
- Ruby Qt tutorial
- Visual Basic Qyoto tutorial
- Mono IronPython Winforms tutorial
- Introduction
- First steps in IronPython Mono Winforms
- Layout management
- Menus and toolbars
- Basic Controls in Mono Winforms
- Basic Controls II in Mono Winforms
- Advanced Controls in Mono Winforms
- Dialogs
- Drag & drop in Mono Winforms
- Painting
- Painting II in IronPython Mono Winforms
- Snake in IronPython Mono Winforms
- The Tetris game in IronPython Mono Winforms
- FreeBASIC GTK tutorial
- Jython Swing tutorial
- JRuby Swing tutorial
- Visual Basic Winforms tutorial
- JavaScript GTK tutorial
- Ruby HTTPClient tutorial
- Ruby Faraday tutorial
- Ruby Net::HTTP tutorial
- Java 2D games tutorial
- Java 2D tutorial
- Cairo graphics tutorial
- PyCairo tutorial
- HTML5 canvas tutorial
- Python tutorial
- Python language
- Interactive Python
- Python lexical structure
- Python data types
- Strings in Python
- Python lists
- Python dictionaries
- Python operators
- Keywords in Python
- Functions in Python
- Files in Python
- Object-oriented programming in Python
- Modules
- Packages in Python
- Exceptions in Python
- Iterators and Generators
- Introspection in Python
- Ruby tutorial
- PHP tutorial
- Visual Basic tutorial
- Visual Basic
- Visual Basic lexical structure
- Basics
- Visual Basic data types
- Strings in Visual Basic
- Operators
- Flow control
- Visual Basic arrays
- Procedures & functions in Visual Basic
- Organizing code in Visual Basic
- Object-oriented programming
- Object-oriented programming II in Visual Basic
- Collections in Visual Basic
- Input & output
- Tcl tutorial
- C# tutorial
- Java tutorial
- AWK tutorial
- Jetty tutorial
- Tomcat Derby tutorial
- Jtwig tutorial
- Android tutorial
- Introduction to Android development
- First Android application
- Android Button widgets
- Android Intents
- Layout management in Android
- Android Spinner widget
- SeekBar widget
- Android ProgressBar widget
- Android ListView widget
- Android Pickers
- Android menus
- Dialogs
- Drawing in Android
- Java EE 5 tutorials
- Introduction
- Installing Java
- Installing NetBeans 6
- Java Application Servers
- Resin CGIServlet
- JavaServer Pages, (JSPs)
- Implicit objects in JSPs
- Shopping cart
- JSP & MySQL Database
- Java Servlets
- Sending email in a Servlet
- Creating a captcha in a Servlet
- DataSource & DriverManager
- Java Beans
- Custom JSP tags
- Object relational mapping with iBATIS
- Jsoup tutorial
- MySQL tutorial
- MySQL quick tutorial
- MySQL storage engines
- MySQL data types
- Creating, altering and dropping tables in MySQL
- MySQL expressions
- Inserting, updating, and deleting data in MySQL
- The SELECT statement in MySQL
- MySQL subqueries
- MySQL constraints
- Exporting and importing data in MySQL
- Joining tables in MySQL
- MySQL functions
- Views in MySQL
- Transactions in MySQL
- MySQL stored routines
- MySQL Python tutorial
- MySQL Perl tutorial
- MySQL C API programming tutorial
- MySQL Visual Basic tutorial
- MySQL PHP tutorial
- MySQL Java tutorial
- MySQL Ruby tutorial
- MySQL C# tutorial
- SQLite tutorial
- SQLite C tutorial
- SQLite PHP tutorial
- SQLite Python tutorial
- SQLite Perl tutorial
- SQLite Ruby tutorial
- SQLite C# tutorial
- SQLite Visual Basic tutorial
- PostgreSQL C tutorial
- PostgreSQL Python tutorial
- PostgreSQL Ruby tutorial
- PostgreSQL PHP tutorial
- PostgreSQL Java tutorial
- Apache Derby tutorial
- SQLAlchemy tutorial
- MongoDB PHP tutorial
- MongoDB Java tutorial
- MongoDB JavaScript tutorial
- MongoDB Ruby tutorial
- Spring JdbcTemplate tutorial
- JDBI tutorial
MongoDB PHP tutorial
In this tutorial we show how to work with MongoDB in PHP. We use the new mongodb
driver for PHP. There is a concise PHP tutorial on ZetCode.
MongoDB is a NoSQL cross-platform document-oriented database. It is one of the most popular databases available. MongoDB is developed by MongoDB Inc. and is published as free and open-source software.
A record in MongoDB is a document, which is a data structure composed of field and value pairs. MongoDB documents are similar to JSON objects. The values of fields may include other documents, arrays, and arrays of documents. MongoDB stores documents in collections. Collections are analogous to tables in relational databases and documents to rows.
Installing MongoDB
The following command can be used to install MongoDB on a Debian-based Linux.
$ sudo apt-get install mongodb
The command installs the necessary packages that come with MongoDB.
$ sudo service mongodb status mongodb start/running, process 975
With the sudo service mongodb status
command we check the status of the mongodb
server.
$ sudo service mongodb start mongodb start/running, process 6448
The mongodb
server is started with the sudo service mongodb start
command.
Creating a database
The mongo
tool is an interactive JavaScript shell interface to MongoDB, which provides an interface for systems administrators as well as a way for developers to test queries and operations directly with the database.
$ mongo testdb MongoDB shell version: 2.4.9 connecting to: testdb > db testdb > db.cars.insert({name: "Audi", price: 52642}) > db.cars.insert({name: "Mercedes", price: 57127}) > db.cars.insert({name: "Skoda", price: 9000}) > db.cars.insert({name: "Volvo", price: 29000}) > db.cars.insert({name: "Bentley", price: 350000}) > db.cars.insert({name: "Citroen", price: 21000}) > db.cars.insert({name: "Hummer", price: 41400}) > db.cars.insert({name: "Volkswagen", price: 21600})
We create a testdb
database and insert eight documents in the cars
collection.
Installing PHP driver
There are two drivers available: the legacy mongo
driver and the new mongodb
driver. In this tutorial, we work with the new mongodb
driver.
Next, we show how to manually install the PHP MongoDB driver.
$ git clone https://github.com/mongodb/mongo-php-driver.git $ cd mongo-php-driver $ git submodule sync && git submodule update --init $ phpize $ ./configure $ make $ sudo make install
We download the sources and install the driver from them.
extension=mongodb.so
We add the mongodb.so
extension to the php.ini
file.
Database statistics
The first example connects to the testdb
database and gets its statistics.
MongoDB\Driver\Manager
is responsible for maintaining connections to MongoDB. MongoDB\Driver\Command
represents a database command. On success, the command returns MongoDB\Driver\Cursor
.
dbstats.php
<?php try { $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $stats = new MongoDB\Driver\Command(["dbstats" => 1]); $res = $mng->executeCommand("testdb", $stats); $stats = current($res->toArray()); print_r($stats); } catch (MongoDB\Driver\Exception\Exception $e) { $filename = basename(__FILE__); echo "The $filename script has experienced an error.\n"; echo "It failed with the following exception:\n"; echo "Exception:", $e->getMessage(), "\n"; echo "In file:", $e->getFile(), "\n"; echo "On line:", $e->getLine(), "\n"; } ?>
The example connects to the testdb
database and executes the dbstats
command. It shows some database statistics.
$mng = new MongoDB\Driver\Manager("mongodb://localhost:27017");
With the MongoDB\Driver\Manager
class, we connect to the testdb
database. The 27017 is the default port on which the MongoDB server listens.
$res = $mng->executeCommand("testdb", $stats);
The MongoDB\Driver\Command
is used to execute the dbstats
command.
$stats = current($res->toArray());
The toArray()
method returns an array containing all results for this cursor and the current()
function returns the array's current element. In our case, the array has one element.
print_r($stats);
The print_r()
function prints a human-readable representation of the $stats
variable.
$ php dbstats.php stdClass Object ( [db] => testdb [collections] => 3 [objects] => 12 [avgObjSize] => 52.666666666667 [dataSize] => 632 [storageSize] => 12288 [numExtents] => 3 [indexes] => 1 [indexSize] => 8176 [fileSize] => 201326592 [nsSizeMB] => 16 [dataFileVersion] => stdClass Object ( [major] => 4 [minor] => 5 ) [ok] => 1 )
This is the output of the dbstats.php
program.
Listing databases
The listDatabases
command provides a list of all existing databases.
list_databases.php
<?php try { $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $listdatabases = new MongoDB\Driver\Command(["listDatabases" => 1]); $res = $mng->executeCommand("admin", $listdatabases); $databases = current($res->toArray()); foreach ($databases->databases as $el) { echo $el->name . "\n"; } } catch (MongoDB\Driver\Exception\Exception $e) { $filename = basename(__FILE__); echo "The $filename script has experienced an error.\n"; echo "It failed with the following exception:\n"; echo "Exception:", $e->getMessage(), "\n"; echo "In file:", $e->getFile(), "\n"; echo "On line:", $e->getLine(), "\n"; } ?>
The example prints available databases in MongoDB.
$listdatabases = new MongoDB\Driver\Command(["listDatabases" => 1]); $res = $mng->executeCommand("admin", $listdatabases);
We execute the listDatabases
command. The command is executed on the admin
database.
$databases = current($res->toArray());
The command returns a single result document, which contains the information for all databases in the databases
array field.
foreach ($databases->databases as $el) { echo $el->name . "\n"; }
We go through the databases array and print the names of the available databases.
$ php list_databases.php testdb test local
On our local machine, we have these three databases.
Reading data
MongoDB\Driver\Query
is a value object that represents a database query.
read_all.php
<?php try { $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $query = new MongoDB\Driver\Query([]); $rows = $mng->executeQuery("testdb.cars", $query); foreach ($rows as $row) { echo "$row->name : $row->price\n"; } } catch (MongoDB\Driver\Exception\Exception $e) { $filename = basename(__FILE__); echo "The $filename script has experienced an error.\n"; echo "It failed with the following exception:\n"; echo "Exception:", $e->getMessage(), "\n"; echo "In file:", $e->getFile(), "\n"; echo "On line:", $e->getLine(), "\n"; } ?>
The example reads all data from the testdb.cars
collection.
$query = new MongoDB\Driver\Query([]);
A MongoDB\Driver\Query
object is created. If we pass an empty array, it reads all data.
$rows = $mng->executeQuery("testdb.cars", $query);
The executeQuery()
executes the query. The first parameter is the collection name and the second parameter is the query.
foreach ($rows as $row) { echo "$row->name : $row->price\n"; }
We iterate over all matched documents.
$ php read_all.php Audi : 52642 Mercedes : 57127 Skoda : 9000 Volvo : 29000 Bentley : 350000 Citroen : 21000 Hummer : 41400 Volkswagen : 21600
This is the output of the read_all.php
script.
Filtering data
The MongoDB\Driver\Query
contains a filter parameter which is used to filter the data.
filtering.php
<?php try { $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $filter = [ 'name' => 'Volkswagen' ]; $query = new MongoDB\Driver\Query($filter); $res = $mng->executeQuery("testdb.cars", $query); $car = current($res->toArray()); if (!empty($car)) { echo $car->name, ": ", $car->price, PHP_EOL; } else { echo "No match found\n"; } } catch (MongoDB\Driver\Exception\Exception $e) { $filename = basename(__FILE__); echo "The $filename script has experienced an error.\n"; echo "It failed with the following exception:\n"; echo "Exception:", $e->getMessage(), "\n"; echo "In file:", $e->getFile(), "\n"; echo "On line:", $e->getLine(), "\n"; } ?>
The example searches for the price of a Volkswagen car.
$filter = [ 'name' => 'Volkswagen' ]; $query = new MongoDB\Driver\Query($filter);
We provide the filter parameter to the MongoDB\Driver\Query
.
$car = current($res->toArray()); if (!empty($car)) { echo $car->name, ": ", $car->price, PHP_EOL; } else { echo "No match found\n"; }
We print the name and the price of the chosen car. We ensure that the returned variable is not empty with the empty()
function.
$ php filtering.php Volkswagen: 21600
This is the output of the filtering.php
script.
Projections
Projections can be used to specify which fields should be returned.
projection.php
<?php try { $filter = []; $options = ["projection" => ['_id' => 0]]; $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $query = new MongoDB\Driver\Query($filter, $options); $rows = $mng->executeQuery("testdb.cars", $query); foreach ($rows as $row) { print_r($row); } } catch (MongoDB\Driver\Exception\Exception $e) { $filename = basename(__FILE__); echo "The $filename script has experienced an error.\n"; echo "It failed with the following exception:\n"; echo "Exception:", $e->getMessage(), "\n"; echo "In file:", $e->getFile(), "\n"; echo "On line:", $e->getLine(), "\n"; } ?>
In the example, we hide the first field—the _id
.
$options = ["projection" => ['_id' => 0]];
Projections are specified in a projection
array. Here we hide the _id
field.
$query = new MongoDB\Driver\Query($filter, $options);
The projections are passed in the second argument of the MongoDB\Driver\Query
.
$ php projection.php stdClass Object ( [name] => Audi [price] => 52642 ) stdClass Object ( [name] => Mercedes [price] => 57127 ) ...
This is the partial output of the projection.php
script. Only the name and price fields are returned.
Limiting data output
The limit
query option specifies the number of documents to be returned and the sort
option the sort order.
read_limit.php
<?php try { $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $query = new MongoDB\Driver\Query([], ['sort' => [ 'name' => 1], 'limit' => 5]); $rows = $mng->executeQuery("testdb.cars", $query); foreach ($rows as $row) { echo "$row->name : $row->price\n"; } } catch (MongoDB\Driver\Exception\Exception $e) { $filename = basename(__FILE__); echo "The $filename script has experienced an error.\n"; echo "It failed with the following exception:\n"; echo "Exception:", $e->getMessage(), "\n"; echo "In file:", $e->getFile(), "\n"; echo "On line:", $e->getLine(), "\n"; } ?>
The example reads all data from the testdb.cars
collection, limits the output to five cars, and sorts according to the car name in ascending order.
$query = new MongoDB\Driver\Query([], ['sort' => [ 'name' => 1], 'limit' => 5]);
We specify the sort
and limit
options in the second parameter of the query.
$ php read_limit.php Audi : 52642 Bentley : 350000 Citroen : 21000 Hummer : 41400 Mercedes : 57127
This is the output of the read_limit.php
script.
Bulk write
The MongoDB\Driver\Manager::executeBulkWrite
method executes one or more write operations, including inserts, updates, and deletes.
bulkwrite.php
<?php try { $mng = new MongoDB\Driver\Manager("mongodb://localhost:27017"); $bulk = new MongoDB\Driver\BulkWrite; $doc = ['_id' => new MongoDB\BSON\ObjectID, 'name' => 'Toyota', 'price' => 26700]; $bulk->insert($doc); $bulk->update(['name' => 'Audi'], ['$set' => ['price' => 52000]]); $bulk->delete(['name' => 'Hummer']); $mng->executeBulkWrite('testdb.cars', $bulk); } catch (MongoDB\Driver\Exception\Exception $e) { $filename = basename(__FILE__); echo "The $filename script has experienced an error.\n"; echo "It failed with the following exception:\n"; echo "Exception:", $e->getMessage(), "\n"; echo "In file:", $e->getFile(), "\n"; echo "On line:", $e->getLine(), "\n"; } ?>
The script inserts a new car, updates one car, and deletes one car.
$bulk = new MongoDB\Driver\BulkWrite();
The MongoDB\Driver\BulkWrite
collects one or more write operations that should be sent to the server.
$doc = ['_id' => new MongoDB\BSON\ObjectID, 'name' => 'Toyota', 'price' => 26700];
This is a new document to be inserted. The MongoDB\BSON\ObjectID
generates a new ObjectId. It is a value used to uniquely identify documents in a collection.
$bulk->insert($doc);
An insert operation is created with the insert()
method.
$bulk->update(['name' => 'Audi'], ['$set' => ['price' => 52000]]);
An update operation is created with the update()
method. The $set
operator replaces the value of a field with the specified value.
$bulk->delete(['name' => 'Hummer']);
A delete operation is created with the delete()
method.
$mng->executeBulkWrite('testdb.cars', $bulk);
The executeBulkWrite()
executes the three operations on the testdb.cars
collection.
> db.cars.find() { "_id" : ObjectId("571e05a6c4a3bc7dc758b457"), "name" : "Audi", "price" : 52000 } { "_id" : ObjectId("571e05b5c4a3bc7dc758b458"), "name" : "Mercedes", "price" : 57127 } { "_id" : ObjectId("571e05bec4a3bc7dc758b459"), "name" : "Skoda", "price" : 9000 } { "_id" : ObjectId("571e05c7c4a3bc7dc758b45a"), "name" : "Volvo", "price" : 29000 } { "_id" : ObjectId("571e05d0c4a3bc7dc758b45b"), "name" : "Bentley", "price" : 350000 } { "_id" : ObjectId("571e05e0c4a3bc7dc758b45c"), "name" : "Citroen", "price" : 21000 } { "_id" : ObjectId("571e05fcc4a3bc7dc758b45e"), "name" : "Volkswagen", "price" : 21600 } { "_id" : ObjectId("5720a4e581365b0e9414d0e1"), "name" : "Toyota", "price" : 26700 }
With the mongo
tool we confirm the changes.
In this tutorial, we have worked with MongoDB and PHP.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论