大网数据广告活动
PHP 语言与运行手册

CollectionModify::arrayInsert · Insert element into an array field

· 52CE 我爱测

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

CollectionModify::arrayInsert

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

CollectionModify::arrayInsert — Insert element into an array field

Description

public function mysql_xdevapi\CollectionModify::arrayInsert(string $collection_field, string $expression_or_literal): mysql_xdevapi\CollectionModify

Adds an element to a document's field, as multiple elements of a field are represented as an array. Unlike mysql_xdevapi\CollectionModify::arrayAppend() this method allows to specify where the new element is inserted by defining which item it is after, whereas mysql_xdevapi\CollectionModify::arrayAppend() always appends the new element at the end of the array.

Parameters

collection_field

Identifies the item in the array after which the new element will be inserted. The format of this parameter is FIELD_NAME[ INDEX ] where FIELD_NAME is the name of the document field to add the element to, and INDEX is the INDEX of the element within the field.

The INDEX field is zero based, so the first item of the array has an index of 0.

expression_or_literal

The new element to insert after FIELD_NAME[ INDEX ]

Return Values

A CollectionModify object that can be used to execute the command, or to add additional operations

Examples

Example #1 mysql_xdevapi\CollectionModify::arrayInsert() example

<?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");
$collection = $schema->createCollection("people");

$result = $collection
  ->add(
  '{"name":   "Bernie",
    "traits": ["Friend", "Brother", "Human"]}') 
  ->execute();

$collection
  ->modify("name in ('Bernie', 'Jane')")
  ->arrayInsert('traits[1]', 'Happy')
  ->execute();

$result = $collection
  ->find()
  ->execute();

print_r($result->fetchAll());
?>

The above example will output something similar to:

Array
(
    [0] => Array
        (
            [_id] => 00005b6b5361000000000000010d
            [name] => Bernie
            [traits] => Array
                (
                    [0] => Friend
                    [1] => Happy
                    [2] => Brother
                    [3] => Human
                )
        )
)

来源:PHP Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。