Start a new topic

Ids as integer


Since MongoDB uses strings as ids, could you tell me what's the best way to use them in Android. For instance, ListView adapters use long id.



I usually either use the index of the element in the array (or list), or just increment a long and add it to the elements.

As an alternative, you can treat the `_id` string as a hexadecimal and try something like this-- although there is no guarantee you will not run into overflow issues:
Thank you Edward !

Yes, converting hexa to long is dangerous.

If I have not all the elements stored in Java, I will need to get the max of a column "id" (not "_id") using aggregate then I will be able to insert a new record using this max+1. Is it ok ?

This is not my case but if we have 2 users userA and userB :

1. userA gets the max : 536

2. userB gets the max : 536

3. userA inserts a record with id=536

4. userB inserts a record with id=536 :(
A modification of the above is to insert a `dummy` record with the new retrieved ID, which would increment the max. Then when the actual entity it saved, it could just replace the `dummy` one.

Another possibility is to investigate UUID.randomUUID (), which, according to google, should not have any collisions.

Also, you can check out android's secure random functionality, which might give you some uniqueness.
Thank you ! There is no way to add an auto increment using a hook ?
you can use the findandmodify method described here:

which you can use to autoincrement on a presave request.
Thanks, I will try :)
Login or Signup to post a comment