You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP文件向MongoDB的testData集合写入经纬度数据失败求助

问题排查与修复方案

我一眼就看到了导致经纬度无法写入MongoDB集合的问题——你插入文档的代码写法完全错了!咱们一步步来修正:

核心错误分析

你当前的插入代码:

$manager->$collection->insert($document);

这里有两个关键问题:

  1. 对象调用方式错误:$collection已经是你通过new MongoDB\Collection(...)创建好的集合实例,不需要再通过$manager去调用它,直接使用$collection对象操作即可。
  2. 方法名过时:新版MongoDB PHP扩展中,Collection类的单文档插入方法是insertOne(),而不是旧版的insert()。

修正后的插入代码

把错误的插入代码替换成:

$collection->insertOne($document);

完整修正后的代码

这里是调整后的完整代码,我还帮你加上了错误提示(方便调试):

<html>
<head>
<title>Unpack</title>
</head>
<body>
<?php
// 开启错误提示,方便调试
error_reporting(E_ALL);
ini_set('display_errors', 1);

//connect to DB
$user = "muntean";
require '/var/composer/vendor/autoload.php';
$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
echo "Connection to database successfully<br>";
$collection = new MongoDB\Collection($manager, $user, 'testData');

//get data from the address bar: e049d3c02b7f5542
$_data = $_GET["data"];
$coord = unpack('flat/flon', pack('H*', $_data));
$lt = $coord['lat'];
$lg = $coord['lon'];
echo "Latitude: $lt<br>";
echo "Longitude: $lg<br>";

// 修正后的插入逻辑
$document = array( "Latitude" => $lt, "Longitude" => $lg );
$insertResult = $collection->insertOne($document);
// 可以打印插入结果,确认是否成功
echo "Inserted document ID: " . $insertResult->getInsertedId() . "<br>";

//shows contect of testData when not empty
$filter = [];
$options = [];
$query = new MongoDB\Driver\Query($filter, $options);
$cursor = $manager->executeQuery("$user.testData", $query);
print("<br>The contents of the collection $user.testData are:<br>");
print_r($cursor->toArray());
?>
</body>
</html>

额外说明

  • 我添加了$insertResult并打印插入ID,这样你可以直观确认文档是否成功写入。
  • 开启错误提示后,如果还有权限或者其他问题,会直接显示错误信息,方便你进一步排查。

内容的提问来源于stack exchange,提问作者Aran Smeallie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:02:49