0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPからMongoDBのCRUD操作を行う / MongoDB CRUD Operations on PHP

Last updated at Posted at 2021-04-08

Create

ドキュメントを1件だけ登録する / Insert a document.

$insertOneResult = $collection -> insertOne(['name' => 'Alice', 'state' => 'ny']);

 "_id"を指定して登録することもできます。その際、登録先のコレクション内で _id が重複しないかチェックされます。もし重複した場合は登録に失敗し、エラーを返します。

 You can use '_id' in query. It is denied and returns errors if the '_id' already exists.

複数件のドキュメントを登録する / Insert documents.

 引数は配列として渡してください / Array is needed to argument.

  $collection -> insertMany( array(['name' => 'Alice', 'state' => 'ny'],
                                   ['name' => 'Bobby', 'state' => 'ny'],
                                   ['name' => 'Cliff', 'state' => 'ca'],
                                   ['name' => 'Dainel','state' => 'wa'],
                                   ['name' => 'Edgar', 'state' => 'az'],
                                   ['name' => 'Greg',  'state' => 'fl'],
                                   ['name' => 'Hilary','state' => 'ny'],
                                   ['name' => 'Ian',   'state' => 'or'],
                                   ['name' => 'Jack',  'state' => 'ny']
                                  ) );

Read ( Find )

条件に合致する全てのドキュメントを出力 / Find and get every documents matched.

$result = $collection -> find(['state' => 'ny']);

条件に合致した先頭行のドキュメントのみを出力 / Find and get the first document matched.

$result = $collection -> findOne(['name' => 'Alice']);

 上記の方法では合致したドキュメントの全てのフィールドが出力されます。もしフィールドを指定する場合は次の様に指定します。(これをプロジェクションと呼びます。)

You write codes like the following if you want filtered documents and fields.

  $findResult = $collection -> find(
                  [
                    'state'=>'ny'
                  ],
                  [
                    'projection' => [
                      '_id'  => 0,
                      'name' => 1,
                      'state'=> 1
                    ],
                    'limit' => 2
                  ]);

Update

ドキュメントの値を更新する / Update the value of document.

  $results = $collection -> updateOne(
    [
       'name' => 'Bobby'                // Query
    ],
    [
       '$set' => [ 'state' => 'wa' ]    // The 'state' field of document's is updated 'wa' if matched.
    ]
  );

$MongoDBクラスにはゲッターが用意されており、以下を利用することでマッチ数と修正数を確認することができます。(今回、$collectionはMongoDBクラスのインスタンスとして定義されています。)

 MongoDB class has some getter functions. You can know how many documents matched and modified if you execute the following functions. ( $collection is an instance of MongoDB class )

  echo $results -> getMatchedCount()."<br>";
  echo $results -> getModifiedCount();

Delete

全件消去 / Delete all documents of the collection unconditionally.

$collection -> drop();

条件を指定して1件のみ消去 / Delete the first document matched.

'state' === 'ny' の最初の1件のみ消去

$collection -> deleteOne(['state' => 'ny']);

条件を指定して全件消去 / Delete every documents matched.

'state' === 'ny' に該当する全てを消去

$collection -> deleteMany(['state' => 'ny']);

前提条件

require 'vendor/autoload.php'; // include Composer's autoloader
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client -> dbName -> collectionName;

筆者の環境 / Environment of computers.

macOS Catalina and PHP ver 8.0.3 installed with brew
MongoDB ver 4.4.3 on PHP built-in web server installed with Composer

参考文献 / References

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?