Collection::add

(No version information available, might only be in Git)

Collection::addコレクションにドキュメントを追加する

説明

public mysql_xdevapi\Collection::add(mixed $document): mysql_xdevapi\CollectionAdd

与えられたドキュメントをドキュメントに追加します。 このメソッドでは、複数のバリエーションがサポートされています。 オプションは以下です:

  1. JSON 文字列として単一のドキュメントを追加する

  2. 単一のドキュメントを次のようにして配列で追加する: [ 'field' => 'value', 'field2' => 'value2' ... ]

  3. 上記2つの組み合わせ。 そして、複数のドキュメントが同じ操作で追加できます。

パラメータ

document

ひとつまたは複数のドキュメント。そして、ドキュメントは JSON または フィールドとそれに関連した値を格納した配列 として表現できます。 空の配列は受け入れられません。

MySQL サーバーは、ドキュメントごとに(推奨)自動的にユニークな _id 値を生成します。 しかし、これは手動でも追加できます。 この値はユニークでなければなりません。ユニークでない場合、操作は失敗します。

戻り値

CollectionAdd オブジェクトを返します。 影響を受けた行を調べたり、操作によって生成された警告の数を得たり、 挿入されたドキュメントのために生成された _id のリストを得るための Result オブジェクトを得るためには、 execute() を使ってください。

例1 mysql_xdevapi\Collection::add() の例

<?php
$session
= mysql_xdevapi\getSession("mysqlx://user:password@localhost");
$session->sql("DROP DATABASE IF EXISTS addressbook")->execute();
$session->sql("CREATE DATABASE addressbook")->execute();

$schema = $session->getSchema("addressbook");
$create = $schema->createCollection("people");

$collection = $schema->getCollection("people");

// ふたつのドキュメントを追加
$collection->add('{"name": "Fred", "age": 21, "job": "Construction"}')->execute();
$collection->add('{"name": "Wilma", "age": 23, "job": "Teacher"}')->execute();

// JSON オブジェクトをひとつ使い、ドキュメントを2つ追加
$result = $collection->add(
'{"name": "Bernie",
"jobs": [{"title":"Cat Herder","Salary":42000}, {"title":"Father","Salary":0}],
"hobbies": ["Sports","Making cupcakes"]}'
,
'{"name": "Jane",
"jobs": [{"title":"Scientist","Salary":18000}, {"title":"Mother","Salary":0}],
"hobbies": ["Walking","Making pies"]}'
)->execute();

// 最後の add() から生成されたIDのリストを取得
$ids = $result->getGeneratedIds();
print_r($ids);
?>

上の例の出力は、 たとえば以下のようになります。

Array
(
    [0] => 00005b6b53610000000000000056
    [1] => 00005b6b53610000000000000057
)

注意

注意:

例で示しているように、ユニークな _id が MySQL サーバー8.0以降では生成されます。 _id フィールドは MySQLサーバー 5.7 を使っている場合は手動で定義しなければなりません。

add a note add a note

User Contributed Notes 2 notes

up
-1
cyork at echodreamz dot com
5 years ago
Seems that (at least with MySQL 5.7.23) if you do not set an _id field in the array of items to "add", it fails with error...

[HY000] Document is missing a required field

Adding "_id" => xxxx does resolve the issue.
up
-1
jcastro at eftec dot cl
5 years ago
It returns a mysql_xdevapi\CollectionAdd instead of a mysql_xdevapi\Result
To Top