Last active
August 29, 2015 14:05
-
-
Save mgng/373b87703ee0f76b828e to your computer and use it in GitHub Desktop.
MongoDB $setOnInsert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// 接続 | |
$dns = "mongodb://localhost:27017"; | |
$Mongo = new \MongoClient( "mongodb://localhost:27017" ); | |
$table = $Mongo->selectCollection( "testdb", "table" ); | |
// user_id = mgng のデータがあれば update, なければ insert ( upsert ) | |
$where = [ 'user_id' => 'mgng' ]; | |
$set = [ | |
'$set' => [ | |
'update_time' => time(), | |
], | |
'$setOnInsert' => [ | |
'user_id' => 'mgng', | |
'created_time' => time(), | |
], | |
]; | |
$options = [ 'upsert' => true ]; | |
$table->update( $where, $set, $options ); | |
// 2秒スリープ | |
sleep( 2 ); | |
// 再度実行 | |
$set = [ | |
'$set' => [ | |
'update_time' => time(), | |
], | |
'$setOnInsert' => [ | |
'user_id' => 'mgng', | |
'created_time' => time(), | |
], | |
]; | |
$table->update( $where, $set, $options ); | |
// データ表示 | |
$cursor = $table->find(); | |
print_r( iterator_to_array( $cursor ) ); | |
/* | |
Array | |
( | |
[53fbe27d38de70e2fcba8d3f] => Array | |
( | |
[_id] => MongoId Object | |
( | |
[$id] => 53fbe27d38de70e2fcba8d3f | |
) | |
[user_id] => mgng | |
[update_time] => 1409016447 | |
[created_time] => 1409016445 | |
) | |
) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment