【发布时间】: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' => $authors的行。 -
也许你想要
collection.insertMany()- 你想要一个文档中的所有作者还是一对? -
你可以尝试像'authors' => [$authors]
-
1 个文档的多个作者