How to create an integer Id generator?

As you know, the mongoDb driver by default does not support automatic integer generation of Id. I spent 2 days thinking about how to implement my own unique integer identifier identifier generator. So how to do this?

+6
source share
4 answers

It’s not a good practice to automatically increase Id in MongoDB, since I will be sick when scaling your server, but if you want to make the value of automatic increase, it is inappropriate to iterate your collection. Instead, make a separate table (sequence, for example) and read the value from there and increase it with findAndModify. It will be unique for each table.

> db.counters.insert({_id: "userId", c: 0}); > var o = db.counters.findAndModify( ... {query: {_id: "userId"}, update: {$inc: {c: 1}}}); { "_id" : "userId", "c" : 0 } > db.mycollection.insert({_id:oc, stuff:"abc"}); > o = db.counters.findAndModify( ... {query: {_id: "userId"}, update: {$inc: {c: 1}}}); { "_id" : "userId", "c" : 1 } > db.mycollection.insert({_id:oc, stuff:"another one"}); 
+5
source

I would use a GUID as a primary key instead of an integer. It has basically two advantages.

  • It is thread safe
  • You do not need to worry about calculating the next identifier.
  • The code needed to get the new identifier is pretty simple

    Guid.NewGuid ()

Check out this useful CodingHorror article that explains the advantages and disadvantages of using GUIDs over classic integer identifiers.

+1
source

Late answer, but I thought I would post this:

https://github.com/alexjamesbrown/MongDBIntIdGenerator

I started the incremental ID generator.
Note - this is far from ideal, and not what Mongodb was intended for.

0
source

Something like that:

 public class UniqueIntGenerator : IIdGenerator { private static UniqueIntGenerator _instance; public static UniqueIntGenerator Instance { get { return _instance; } } static UniqueIntGenerator() { _instance = new UniqueIntGenerator(); } public object GenerateId(object container, object document) { var cont = container as MongoCollection; if (cont == null) return 0; var type = cont.Settings.DefaultDocumentType; var cursor = cont.FindAllAs(type); cursor.SetSortOrder(SortBy.Descending("_id")); cursor.Limit = 1; foreach (var obj in cursor) return GetId(obj) + 1; return 1; } private int GetId(object obj) { var properties = obj.GetType().GetProperties(); var idProperty = properties.Single(y => y.GetCustomAttributes(typeof(BsonIdAttribute), false).SingleOrDefault() != null); var idValue = (int)idProperty.GetValue(obj, null); return idValue; } public bool IsEmpty(object id) { return default(int) == (int)id; } } 
-4
source

Source: https://habr.com/ru/post/918162/


All Articles