Skip to content

Instantly share code, notes, and snippets.

@komputronika
Last active March 1, 2024 04:56
Show Gist options
  • Select an option

  • Save komputronika/4c4cd222f8e1ed355035754ea6ead8bb to your computer and use it in GitHub Desktop.

Select an option

Save komputronika/4c4cd222f8e1ed355035754ea6ead8bb to your computer and use it in GitHub Desktop.
How to create autoincrement sequence number in MongoDB, with PHP library
<?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