Mongodb self increasing id implementation method

  • 2020-06-12 10:53:29
  • OfStack

An example of Mongodb self-augmentation id is presented. To share for your reference, specific as follows:

First, create an auto-growing id collection, ids


>db.ids.save({name:"user", id:0});

You can check to see if 1 was successful


> db.ids.find();
{ "_id" : ObjectId("4c637dbd900f00000000686c"), "name" : "user", "id" : 0 }

The ids collection is then acquired by adding 1 ids before each new user is added

The name="user" document in the ES19en.ids collection plus 1 each time a new user is added to the db.user collection returns the document


>userid = db.ids .findAndModify({update:{$inc:{'id':1}}, query:{"name":"user"}, new:true});
{ "_id" : ObjectId("4c637dbd900f00000000686c"), "name" : "user", "id" : 1 }

Note: Since findAndModify is one method to complete two operations of update lookup, it is atomic and multithreading does not conflict.

Then save the corresponding data


>db.user .save({uid:userid.id, username:"dotcoo", password:"dotcoo", info:"https://www.ofstack.com/ "});
// --------- update 2011-03-27 13:11 ------------------------

I could actually write the top two lines as 1 step


>db.user .save({
  uid: db.ids .findAndModify({
    update:{$inc:{'id':1}},
    query:{"name":"user"},
    new:true}).id, // let db.ids In the collection name="user" The document id Value added 1 And returns as an autoincrement id
  username: "dotcoo",
  password:"dotcoo",
  info:"https://www.ofstack.com/  "});
// --------- update 2011-03-27 13:11 ------------------------

View the results


> db.user.find();
{ "_id" : ObjectId("4c637f79900f00000000686d"), "uid" : 1, "username" : "admin", "password" : "admin" }

This is THE shell of mongo. If you are using the server-side program Java php Python, you can encapsulate 1 of these operations by yourself. You only need to pass a few parameters to return the self-increasing id.

I have written a paragraph of php for you to share.


<?php
function mid($name, $db){
  $update = array('$inc'=>array("id"=>1));
  $query = array('name'=>$name);
  $command = array(
      'findandmodify'=>'ids', 'update'=>$update,
      'query'=>$query, 'new'=>true, 'upsert'=>true
  );
  $id = $db->command($command);
  return $id['value']['id'];
}
$conn = new Mongo();
$db = $conn->idtest;
$id = mid('user', $db);
$db->user->save(array('uid'=>$id, 'username'=>'kekeles', 'password'=>'kekeles', 'info'=>'https://www.ofstack.com/ '));
$conn->close();
?>

The concrete implementation method is mainly using findAndModify command in MongoDB, as long as ID is generated before insert object in MongoDB to assign value to _id, OK, because its implementation meets atomicity, so there is no concurrency problem.

Another point is that findAndModify itself provides an upsert parameter. If it is true, insert can be automatically used. However, the initial value cannot be customized, so upsert is not used in this example.

BTW, the name of database "_seq" begins with an underscore, so that the list can be sorted first.

I hope this article is helpful to the database programming of MongoDB.


Related articles: