For developers who use mongodb to build their web applications, what do you do with long primary keys?

DBMS identifiers are usually simple integers that go from 0 to any number, but you can usually store them in a 5-digit range so that you can create URLs that look like this

myawesomeblog.com/posts/23456

but with mongodb, the unique identifiers for each entry look like this. 47cc67093475061e3d95369d

and the build and application are based on what will result in such URLs myawesomeblog.com/posts/47cc67093475061e3d95369d

I do not like it? Is there anyway to give mongoes an integer identification number that is shorter and unique? (e.g. MySQL)

+5
source share
3 answers

Here is the link to create an extra value from DOCS

http://www.mongodb.org/display/DOCS/Atomic+Operations#AtomicOperations-%22InsertifNotPresent%22
+1
source

One of the ways I tried (and it seems to work) is to create a collection of sequences with documents like:

{Name: "Messages", Value: 12345, _id: ObjectId ("47cc67093475061e3d95369d")}

Before embedding in the Posts collection, you must grab the current sequence named "Posts" and increase its value. Then use this value as the URL ID or ObjectId for the new Post document.

This approach is similar to using Oracle SELECT seq.NEXTVAL FROM DUAL as primary keys.

, .

+1

Anything that creates an incremental key will not work as soon as you start using replication. I am using something that creates a unique SHA prefix like git. It does not give you an integer key, but it can be easily changed. Also, uniqueness is not guaranteed, but you have much less chance of a collision than using the magnifying key. My model has the following things:

before_create :set_short_id

def set_short_id
  prefix_length = 5
  sha = Digest::SHA1.hexdigest(self.to_json)
  short_id = nil
  while short_id.nil? || Ticket.first(:short_id => short_id)
    short_id = sha.first(prefix_length)
    prefix_length += 1
  end
  self.short_id = short_id
end

def to_param
  short_id
end

That means my urls look like a myawesomeblog.com/posts/47cc6little better.

+1
source

All Articles