是否有可能通过Mongolab的RESTful API在后端使用PHP进行插入


Is it possible to do an INSERT in the backend with PHP via Mongolab's RESTful API?

我想将准备好的JSON发送到后端的PHP脚本,然后使用Mongolab的RESTful API进行插入。我能找到的唯一插入示例是前端 AJAX。

来自 REST API for MongoLab 的示例代码

POST /databases/{database}/collections/{collection}
Content-Type: application/json
Body: <JSON data>
Example (using jQuery):
$.ajax( { url: "https://api.mongolab.com/api/1/databases/my-db/collections/my-coll?apiKey=myAPIKey",
          data: JSON.stringify( { "x" : 1 } ),
          type: "POST",
          contentType: "application/json" } );

不幸的是,与我一起工作的服务器管理员不允许我安装 Mongo PHP 驱动程序来执行此操作,所以我被迫走这条路。

有谁知道这是否可能?

检索数据的示例

$data = file_get_contents('https://api.mongolab.com/api/1/databases/**DATABASE**/collections/**COLLECTION*?q={%22_id%22:{%22$oid%22:%22' . $_GET['id'] . '%22}}&apiKey=**API KEY**');
$obj = json_decode($data);
$obj=$obj[0];
翻译成

PHP的jQuery示例是:

<?php
$key        = "my API key";
$db         = "my-database-name";
$collection = "my-collection-name";
$document = array(
    "x" => 1,
    "more" => array("data", "here"),
);
$opts = array(
    "http" => array(
        "method"  => "POST",
        "header"  => "Content-type: application/json",
        "content" => json_encode($document),
    ),
);
$context = stream_context_create($opts);
$result = file_get_contents("https://api.mongolab.com/api/1/databases/$db/collections/$collection?apiKey=$key", false, $context);
var_dump($result); // Dumps the response document
?>