Databases 3 min read

MongoDB PHP Driver: Insert, Query, Update, and Delete Operations

This article provides a step‑by‑step tutorial on using the MongoDB PHP driver to insert, query, update, and delete documents in the ‘wj’ collection of the ‘test’ database, including full code examples for each CRUD operation.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
MongoDB PHP Driver: Insert, Query, Update, and Delete Operations

In this guide we demonstrate how to use the MongoDB PHP driver to perform basic CRUD operations on a collection named wj in the test database.

1. Insert data

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->insert(['id' => 1, 'name' => '测试', 'url' => 'http://www.百度.com']);
$manager->executeBulkWrite('test.wj', $bulk);

2. Query data (excluding name = '测试')

$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$filter = ['name' => '测试'];
$options = [
    'projection' => ['_id' => 0],
    'sort' => ['name' => -1],
];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery('test.wj', $query);
foreach ($cursor as $document) {
    print_r($document);
}

3. Update data (set name to '测试1234' where id = 1)

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
    ['id' => 1],
    ['$set' => ['name' => '测试1234']],
    ['multi' => false, 'upsert' => false]
);
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.wj', $bulk, $writeConcern);

4. Delete data

$bulk = new MongoDB\Driver\BulkWrite;
$bulk->delete(['id' => 1], ['limit' => 1]); // delete first matching document
$bulk->delete(['id' => 2], ['limit' => 0]); // delete all matching documents
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
$result = $manager->executeBulkWrite('test.wj', $bulk, $writeConcern);
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

databasePHPCRUDMongoDBMongoDB Driver
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.