Last active
March 1, 2024 04:56
-
-
Save komputronika/4c4cd222f8e1ed355035754ea6ead8bb to your computer and use it in GitHub Desktop.
How to create autoincrement sequence number in MongoDB, with PHP library
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 | |
| // Table "counters", stores autoincrement value (seq) | |
| /* | |
| Initial value are: | |
| { | |
| "_id": "nota", // Counter key, eg: 'nota' | |
| "seq": 1 // Initial number | |
| } | |
| */ | |
| //.............. | |
| // Link to table "counters" | |
| $counters = $client->mydatabase->counters; | |
| // Link to any tables | |
| $table = $client->mydatabase->mytable; | |
| // Insert one record to the table | |
| $result = $table->insertOne([ | |
| 'nomor_nota' => getNextSequence( $counters, "nota" ), // Get next autoincrement of 'nota' | |
| 'customer' => 'Udin Balagadona', | |
| 'total' => 5000000 | |
| ]); | |
| //.............. | |
| // Function to get next autoincrement number | |
| function getNextSequence( $counters, $name ) { | |
| $result = $counters->findOneAndUpdate( | |
| [ '_id' => 'nota' ], // Set key as 'nota' | |
| [ '$inc' => [ 'seq' => 1] ], | |
| [ 'upsert' => true, | |
| 'projection' => [ 'seq' => 1 ], | |
| 'returnDocument' => MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER | |
| ] | |
| ); | |
| return $result['seq']; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment