【问题标题】:PHP How to add entire array into MongoDB document fieldPHP如何将整个数组添加到MongoDB文档字段中
【发布时间】:2019-04-10 19:44:17
【问题描述】:

我正在使用php 页面在我的 MongoDB 数据库中插入新文档。我想通过 URI 将一组作者添加到文档字段 (authors:['Sally Sue', 'Billy Bob']) 中。

这是我的 php 页面内容:

<?php
require __DIR__ . '/vendor/autoload.php'; // Composer autoloader

use MongoDB\Driver\Manager as Mongo;

// Set $_GET variables
if (isset($_GET['authors'])){
    $authors = explode(',', filter_var($_GET['authors'], FILTER_SANITIZE_STRING));
} else {
    $authors = 'N/A';
}

$mongo = new Mongo("mongodb://127.0.0.1:27017/myDB");
$db = new MongoDB\Database($mongo, "myDB");    
$collection = $db->selectCollection("articles");
$result = $collection->insertOne([
    'authors' => $authors,
]);

print_r($result);

?>

URI 字符串

http://x.x.x.x/mySite/insertArticle.php?authors=Sally%20Sue,%20Billy%20Bob

但是,代码将我的 $authors 变量作为字符串插入:

Notice: Array to string conversion in /var/www/html/mySite/insertArticle.php on line 17

如何将$authors 变量作为数组插入?我必须使用for 循环还是有办法将整个数组内容作为一个变量一次性插入?

【问题讨论】:

  • 第 61 行是哪一行?
  • 糟糕,应该是16 行。这是'authors' =&gt; $authors 的行。
  • 也许你想要collection.insertMany() - 你想要一个文档中的所有作者还是一对?
  • 你可以尝试像'authors' => [$authors]
  • 1 个文档的多个作者

标签: php arrays mongodb


【解决方案1】:

您可以尝试以下任何一种方式来处理此代码

 ‘authors’ => [$authors]

【讨论】:

  • 请添加到正式 mongoDB 文档的链接 - 这将有助于未来的程序员
  • 我希望伴侣。我在我的手机上,很难按 ctrl + L 什么的。我希望你明白。明天我一定会做的
猜你喜欢
  • 2019-11-12
  • 2016-10-16
  • 1970-01-01
  • 2020-02-23
  • 2014-07-29
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多