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

如何将包含JavaScript函数的MongoDB查询转换为PHP代码?

Hey there! I can help you translate that MongoDB Shell query into working PHP code. Let's start by breaking down what's wrong with your current attempt, then fix it up properly.

Key Issues in Your PHP Code

  • In PHP, all variables need a $ prefix—so your function parameter should be $tweet instead of just tweet.
  • When accessing properties of an object in PHP, you use -> followed directly by the property name (no quotes), like $tweet->_id instead of tweet->"_id".
  • PHP doesn't have a Date() constructor like the MongoDB Shell does. Instead, we'll use either a standard DateTime object or MongoDB's UTCDateTime class to create valid date values that MongoDB can recognize.

Corrected PHP Code (Matching Your Shell Query)

Here's the working version that mirrors your original shell logic:

// Assuming $collection is your initialized MongoDB collection instance
$collection->find()->forEach(function ($tweet) use ($collection) {
    // Parse the string date into a DateTime object
    $parsedDate = new DateTime($tweet->created_at);
    
    // Update the document with the proper date type
    $collection->updateOne(
        ['_id' => $tweet->_id],
        ['$set' => ['created_at' => $parsedDate]]
    );
});

A quick note: The modern MongoDB PHP driver automatically converts DateTime objects to the correct BSON Date type, so no extra conversion steps are needed. If you're using an older driver version, you might need to use MongoDB\BSON\UTCDateTime instead:

['$set' => ['created_at' => new MongoDB\BSON\UTCDateTime($parsedDate->getTimestamp() * 1000)]]

Optimized Approach: Bulk Updates

If you're working with a large collection, looping through each document and updating individually can be slow. For better performance, use bulk operations to batch updates:

$bulkWriter = new MongoDB\Driver\BulkWrite();
$cursor = $collection->find();

foreach ($cursor as $tweet) {
    $parsedDate = new DateTime($tweet->created_at);
    $bulkWriter->update(
        ['_id' => $tweet->_id],
        ['$set' => ['created_at' => $parsedDate]],
        ['multi' => false]
    );
}

// Execute the bulk update (replace with your connection string and database name)
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$result = $manager->executeBulkWrite('your_database_name.sample_collection', $bulkWriter);

This reduces round-trips to the database, making the operation much faster for large datasets.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:03:43