如何将包含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$tweetinstead of justtweet. - When accessing properties of an object in PHP, you use
->followed directly by the property name (no quotes), like$tweet->_idinstead oftweet->"_id". - PHP doesn't have a
Date()constructor like the MongoDB Shell does. Instead, we'll use either a standardDateTimeobject or MongoDB'sUTCDateTimeclass 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

