使用 mongodb PHP 擴展 (非舊版 mongo) 操作 MongoDB 時,常遇到 **Int64 (Long) 型別查詢無結果**、**MapReduce 游標超時** 等問題。本文記錄實戰解決方案。
文件結構:
{
"in_ts": NumberLong("1347349143699"),
"log": {
"stamp": NumberLong("1347349162159") // 原為字串 "1347349162159"
},
"out_ts": NumberLong("1347349466083")
}
<?php $query = ['log.stamp' => ['$gte' => 1347346800000, '$lt' => 1347350400000]]; $cursor = $collection->find($query); // 無結果! ?>
**原因**:PHP 整數在 32 位系統上為 32 位有號整數 (最大 2147483647),13 位時間戳超出範圍會溢位/轉浮點,導致與 MongoDB Int64 不匹配。即使 64 位 PHP,驅動預設也會將整數編碼為 BSON Int32 或 Int64,但需顯式指定。
<?php
use MongoDB\BSON\Int64;
$start = new Int64('1347346800000');
$end = new Int64('1347350400000');
$query = ['log.stamp' => ['$gte' => $start, '$lt' => $end]];
$cursor = $collection->find($query); // 正確返回結果
?>
MongoDB\BSON\Int64 建構子接受**字串**或**整數** (64 位環境)。**建議傳字串**避免 32 位溢位。new Int64($timestampStr) 確保型別正確。大數據 MapReduce 易觸發 MongoCursorTimeoutException。在 command() 選項中設定 timeout (毫秒)。
<?php
use MongoDB\BSON\Javascript; // MongoCode 已棄用
$map = new Javascript('function() {
var propId = this.log.cstparam.proId;
var key = this.log.site + propId;
emit(key, {channel: this.log.site, prop_id: propId, count: 1});
}');
$reduce = new Javascript('function(key, emits) {
var total = 0;
for (var i in emits) total += emits[i].count;
return {channel: emits[0].channel, prop_id: emits[0].prop_id, count: total};
}');
$cmd = [
'mapreduce' => $collectionName,
'map' => $map,
'reduce' => $reduce,
'out' => $tmpResultCollection,
'query' => $query,
];
// 設定超時 10 分鐘 (600000 ms)
$options = ['timeout' => 600000];
$result = $db->command($cmd, $options);
?>
MongoCode 已棄用,改用 MongoDB\BSON\Javascript。timeout 單位為**毫秒**,依資料量調整 (預設 30000ms 太短)。new MongoDB\BSON\ObjectId() 或 MongoDB\BSON\ObjectId::generate()。MongoDB\BSON\UTCDateTime (毫秒時間戳) 而非 PHP DateTime 物件直接存入。['projection' => ['field' => 1]] 減少網傳資料。$bulk = new MongoDB\Driver\BulkWrite; $bulk->insert([...]); $manager->executeBulkWrite('db.col', $bulk);。new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED) 分散讀取壓力。MongoDB\Driver\Exception\Exception 及子類別 (BulkWriteException, ConnectionException 等)。| 舊版 mongo 擴展 | 新版 mongodb 擴展 (PHP 7+) |
|---|---|
| MongoClient | MongoDB\Client / MongoDB\Driver\Manager |
| MongoCollection | MongoDB\Collection |
| MongoCursor | MongoDB\Driver\Cursor |
| MongoId | MongoDB\BSON\ObjectId |
| MongoDate | MongoDB\BSON\UTCDateTime |
| MongoInt64 / MongoInt32 | MongoDB\BSON\Int64 / Int32 |
| MongoCode | MongoDB\BSON\Javascript |
| MongoRegex | MongoDB\BSON\Regex |