Skip to content

Instantly share code, notes, and snippets.

@mgng
Last active August 29, 2015 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgng/373b87703ee0f76b828e to your computer and use it in GitHub Desktop.
Save mgng/373b87703ee0f76b828e to your computer and use it in GitHub Desktop.
MongoDB $setOnInsert
<?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